ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
refactor(gui): route agent commands through the SDK, and declare them all
Juan Deniscc72494d5924
diff --git a/backend/app/plugins/serverkit-gui/blueprint.py b/backend/app/plugins/serverkit-gui/blueprint.pyindex db54e8dc..d3297554 100644--- a/backend/app/plugins/serverkit-gui/blueprint.py+++ b/backend/app/plugins/serverkit-gui/blueprint.py@@ -1,16 +1,22 @@"""ServerKit Agent GUI plugin — panel-side blueprint.Acts as a thin proxy between the frontend and the agent's gui:* actions.-No frame data is stored; everything is forwarded through agent_registry.send_command.+No frame data is stored; everything is forwarded through plugins_sdk.agents,+which checks this plugin declared ``agent.command:<action>`` before dispatching+and turns a failed command into an exception carrying the reason."""from flask import Blueprint, jsonify, requestfrom flask_jwt_extended import jwt_required, get_jwt_identity-from app.services.agent_registry import agent_registry+from app.plugins_sdk import agents, logger+from app.plugins_sdk.permissions import PermissionDeniedfrom app.models.server import Serverfrom app.models.user import Usergui_bp = Blueprint("server_gui", __name__)+log = logger(__name__)++PLUGIN_SLUG = "serverkit-gui"DEFAULT_FRAME_TIMEOUT = 8.0MAX_FRAME_TIMEOUT = 15.0@@ -20,6 +26,10 @@ def _current_user():return User.query.get(get_jwt_identity())+def _fleet():+ return agents.for_plugin(PLUGIN_SLUG)++def _server_or_404(server_id: str):server = Server.query.get(server_id)if not server:@@ -43,23 +53,23 @@ def capabilities(server_id):"synthetic_fallback": True,})- result = agent_registry.send_command(- server_id=server_id,- action="gui:capabilities",- params={},- timeout=5.0,- user_id=user.id if user else None,- )-- if not result.get("success"):- # Agent doesn't implement gui:capabilities — that's fine, fall back.+ try:+ data = _fleet().run(+ server_id, "gui:capabilities",+ timeout=5.0,+ user_id=user.id if user else None,+ )+ except (agents.CommandError, PermissionDenied) as exc:+ # Not an error state: an agent that doesn't implement gui:capabilities+ # is exactly what the synthetic fallback exists for.return jsonify({"capability": "none",- "reason": result.get("error", "unsupported"),+ "reason": str(exc),"synthetic_fallback": True,})- data = result.get("data") or {}+ if not isinstance(data, dict):+ data = {}data.setdefault("synthetic_fallback", data.get("capability") in (None, "none"))return jsonify(data)@@ -94,25 +104,23 @@ def frame(server_id):if fmt not in ("jpeg", "png"):fmt = "jpeg"- result = agent_registry.send_command(- server_id=server_id,- action="gui:screenshot",- params={"scale": scale, "quality": quality, "format": fmt},- timeout=DEFAULT_FRAME_TIMEOUT,- user_id=user.id if user else None,- )-- if not result.get("success"):- return jsonify({- "error": result.get("error", "capture failed"),- "code": result.get("code", "CAPTURE_FAILED"),- }), 502+ try:+ data = _fleet().run(+ server_id, "gui:screenshot",+ {"scale": scale, "quality": quality, "format": fmt},+ timeout=DEFAULT_FRAME_TIMEOUT,+ user_id=user.id if user else None,+ )+ except PermissionDenied as exc:+ # Only reachable if this plugin's manifest lost the permission.+ return jsonify({"error": str(exc), "code": "PERMISSION_DENIED"}), 403+ except agents.CommandError as exc:+ return jsonify({"error": str(exc), "code": exc.code or "CAPTURE_FAILED"}), 502- data = result.get("data") or {}# Expected agent shape:# { "image_base64": "...", "format": "jpeg", "width": 1920, "height": 1080,# "captured_at": "2026-05-01T12:34:56Z" }- if "image_base64" not in data:+ if not isinstance(data, dict) or "image_base64" not in data:return jsonify({"error": "agent returned no frame"}), 502return jsonify(data)@@ -139,23 +147,33 @@ def synthetic(server_id):"offline": True,})- sysinfo = agent_registry.send_command(- server_id=server_id,- action="system:info",- params={},- timeout=5.0,- user_id=user.id if user else None,- )- procs = agent_registry.send_command(- server_id=server_id,- action="system:processes",- params={"limit": 12},- timeout=5.0,- user_id=user.id if user else None,- )-- info = (sysinfo.get("data") or {}) if sysinfo.get("success") else {}- plist = (procs.get("data") or []) if procs.get("success") else []+ user_id = user.id if user else None++ def _best_effort(action, params, default):+ """Ask the agent, but never fail the page over the answer.++ This endpoint renders *something* for a host with no display, so an+ agent that won't answer degrades to an empty panel rather than an+ error. A permission this plugin hasn't been granted lands in the same+ place deliberately: an install whose stored manifest predates these+ actions keeps working instead of 500-ing, and the log line says why.+ """+ try:+ return _fleet().run(server_id, action, params, timeout=5.0,+ user_id=user_id)+ except PermissionDenied as exc:+ log.warning('%s: %s — update the extension to restore full '+ 'synthetic detail', PLUGIN_SLUG, exc)+ return default+ except agents.CommandError:+ return default++ info = _best_effort("system:info", {}, {})+ plist = _best_effort("system:processes", {"limit": 12}, [])+ if not isinstance(info, dict):+ info = {}+ if not isinstance(plist, list):+ plist = []windows = [{diff --git a/backend/app/plugins/serverkit-gui/plugin.json b/backend/app/plugins/serverkit-gui/plugin.jsonindex 1e8facde..c122b14b 100644--- a/backend/app/plugins/serverkit-gui/plugin.json+++ b/backend/app/plugins/serverkit-gui/plugin.json@@ -13,12 +13,16 @@"frontend_entry": "components/ServerGui.jsx","requires_agent_actions": ["gui:screenshot",- "gui:capabilities"+ "gui:capabilities",+ "system:info",+ "system:processes"],"minimum_agent_version": "0.4.0","permissions": ["agent.command:gui:screenshot",- "agent.command:gui:capabilities"+ "agent.command:gui:capabilities",+ "agent.command:system:info",+ "agent.command:system:processes"],"contributions": {"widgets": [diff --git a/backend/tests/test_serverkit_gui_agent_gate.py b/backend/tests/test_serverkit_gui_agent_gate.pynew file mode 100644index 00000000..31dc9ac1--- /dev/null+++ b/backend/tests/test_serverkit_gui_agent_gate.py@@ -0,0 +1,206 @@+"""serverkit-gui goes through plugins_sdk.agents (retrofit).++The extension used to call the agent registry directly, so its manifest+permissions were decoration: the install dialog said "screenshot and+capabilities" while /synthetic quietly also asked for system:info and+system:processes. Routing through the SDK enforces the declaration, which+first required the manifest to tell the truth.++The case worth protecting is an install whose STORED manifest predates those+two actions — declared_permissions() reads the database row captured at install+time, not plugin.json on disk. /synthetic must degrade there, not 500.+"""++import importlib+import json+import pathlib++import pytest+from flask_jwt_extended import create_access_token++from app import db+from app.models.plugin import InstalledPlugin+from app.models.server import Server+from app.models.user import User+from app.services import agent_registry as agent_registry_module++SLUG = 'serverkit-gui'+SERVER_ID = 'srv-gui-1'+PREFIX = '/api/v1/server-gui'++GUI_ONLY = ['agent.command:gui:screenshot', 'agent.command:gui:capabilities']+ALL_FOUR = GUI_ONLY + ['agent.command:system:info', 'agent.command:system:processes']++_PLUGIN_DIR = pathlib.Path(__file__).resolve().parents[1] / 'app' / 'plugins' / SLUG+++def gui_app(app):+ """The app fixture with the gui blueprint mounted."""+ module = importlib.import_module(f'app.plugins.{SLUG}.blueprint')+ if not any(bp.name == 'server_gui' for bp in app.blueprints.values()):+ app.register_blueprint(module.gui_bp, url_prefix=PREFIX)+ return app+++def headers(gui_app):+ user = User(email='[email protected]', username='gui_admin',+ password_hash='x', role=User.ROLE_ADMIN, is_active=True)+ db.session.add(user)+ db.session.add(Server(id=SERVER_ID, name='box', status='online'))+ db.session.commit()+ return {'Authorization': f'Bearer {create_access_token(identity=user.id)}'}+++def _install(permissions):+ """Install the plugin with a given stored manifest."""+ InstalledPlugin.query.filter_by(slug=SLUG).delete()+ plugin = InstalledPlugin(slug=SLUG, name=SLUG, display_name='GUI',+ version='0.1.0',+ status=InstalledPlugin.STATUS_ACTIVE)+ plugin.manifest = {'permissions': permissions}+ db.session.add(plugin)+ db.session.commit()+ return plugin+++def fleet(monkeypatch):+ registry = agent_registry_module.agent_registry+ replies = {+ 'gui:capabilities': {'success': True, 'data': {'capability': 'x11'}},+ 'gui:screenshot': {'success': True, 'data': {'image_base64': 'AAAA'}},+ 'system:info': {'success': True, 'data': {'hostname': 'realhost'}},+ 'system:processes': {'success': True,+ 'data': [{'pid': 1, 'name': 'sshd'}]},+ }+ state = {'replies': replies, 'asked': []}++ def _send(server_id, action, params=None, timeout=None, user_id=None):+ state['asked'].append(action)+ return state['replies'].get(action, {'success': False, 'error': 'unknown action',+ 'code': 'UNKNOWN'})++ monkeypatch.setattr(registry, 'send_command', _send)+ monkeypatch.setattr(registry, 'is_agent_connected', lambda sid: True)+ monkeypatch.setattr(registry, 'has_capability', lambda sid, cap: True)+ monkeypatch.setattr(registry, 'get_capabilities', lambda sid: {})+ return state+++class TestManifest:+ def _manifest(self, path):+ return json.loads(pathlib.Path(path).read_text(encoding='utf-8'))++ def test_declares_every_action_it_calls(self):+ manifest = self._manifest(_PLUGIN_DIR / 'plugin.json')+ # The retrofit's precondition: the gate can only be honest if the+ # manifest lists what the code actually asks for.+ for action in ('gui:screenshot', 'gui:capabilities',+ 'system:info', 'system:processes'):+ assert f'agent.command:{action}' in manifest['permissions']++ def test_requires_agent_actions_agrees_with_permissions(self):+ manifest = self._manifest(_PLUGIN_DIR / 'plugin.json')+ declared = {p.split('agent.command:', 1)[1]+ for p in manifest['permissions']+ if p.startswith('agent.command:')}+ assert set(manifest['requires_agent_actions']) == declared+++class TestCapabilities:+ def test_returns_the_agents_answer(self, gui_app, client, headers, fleet):+ _install(ALL_FOUR)+ res = client.get(f'{PREFIX}/{SERVER_ID}/capabilities', headers=headers)+ assert res.status_code == 200+ assert res.get_json()['capability'] == 'x11'++ def test_falls_back_when_the_agent_cannot(self, gui_app, client, headers, fleet):+ _install(ALL_FOUR)+ fleet['replies']['gui:capabilities'] = {'success': False,+ 'error': 'unsupported'}+ res = client.get(f'{PREFIX}/{SERVER_ID}/capabilities', headers=headers)+ # Still a 200 with the synthetic fallback — unchanged behaviour.+ assert res.status_code == 200+ assert res.get_json()['synthetic_fallback'] is True++ def test_falls_back_when_the_permission_is_missing(self, gui_app, client,+ headers, fleet):+ _install([])+ res = client.get(f'{PREFIX}/{SERVER_ID}/capabilities', headers=headers)+ assert res.status_code == 200+ assert res.get_json()['synthetic_fallback'] is True+ assert fleet['asked'] == []+++class TestFrame:+ def test_returns_the_frame(self, gui_app, client, headers, fleet):+ _install(ALL_FOUR)+ res = client.get(f'{PREFIX}/{SERVER_ID}/frame', headers=headers)+ assert res.status_code == 200+ assert res.get_json()['image_base64'] == 'AAAA'++ def test_a_failed_capture_is_still_a_502(self, gui_app, client, headers, fleet):+ _install(ALL_FOUR)+ fleet['replies']['gui:screenshot'] = {'success': False, 'error': 'no display',+ 'code': 'CAPTURE_FAILED'}+ res = client.get(f'{PREFIX}/{SERVER_ID}/frame', headers=headers)+ assert res.status_code == 502+ assert res.get_json()['code'] == 'CAPTURE_FAILED'++ def test_a_handler_failure_inside_a_successful_reply_is_reported(+ self, gui_app, client, headers, fleet):+ # Previously this surfaced as the vague "agent returned no frame";+ # the SDK unwraps it, so the real reason reaches the caller.+ fleet['replies']['gui:screenshot'] = {+ 'success': True, 'data': {'success': False, 'error': 'no display'}}+ _install(ALL_FOUR)+ res = client.get(f'{PREFIX}/{SERVER_ID}/frame', headers=headers)+ assert res.status_code == 502+ assert 'no display' in res.get_json()['error']++ def test_a_missing_permission_is_refused_not_dispatched(self, gui_app, client,+ headers, fleet):+ _install([])+ res = client.get(f'{PREFIX}/{SERVER_ID}/frame', headers=headers)+ assert res.status_code == 403+ assert res.get_json()['code'] == 'PERMISSION_DENIED'+ assert fleet['asked'] == []+++class TestSynthetic:+ def test_uses_real_agent_data_when_permitted(self, gui_app, client, headers, fleet):+ _install(ALL_FOUR)+ res = client.get(f'{PREFIX}/{SERVER_ID}/synthetic', headers=headers)+ assert res.status_code == 200+ body = res.get_json()+ assert body['hostname'] == 'realhost'+ assert body['taskbar'] == [{'id': 1, 'name': 'sshd'}]++ def test_an_older_install_degrades_instead_of_failing(self, gui_app, client,+ headers, fleet):+ # The regression this endpoint's fallback exists for: declared+ # permissions come from the DB row captured at install time, so an+ # install predating this change lists only the two gui actions.+ _install(GUI_ONLY)++ res = client.get(f'{PREFIX}/{SERVER_ID}/synthetic', headers=headers)++ assert res.status_code == 200+ body = res.get_json()+ assert body['taskbar'] == []+ assert body['offline'] is False+ assert body['hostname'] == 'box' # falls back to the server's name+ assert fleet['asked'] == []++ def test_a_silent_agent_still_renders_a_desktop(self, gui_app, client,+ headers, fleet):+ _install(ALL_FOUR)+ fleet['replies']['system:info'] = {'success': False, 'error': 'nope'}+ fleet['replies']['system:processes'] = {'success': False, 'error': 'nope'}++ res = client.get(f'{PREFIX}/{SERVER_ID}/synthetic', headers=headers)++ assert res.status_code == 200+ assert res.get_json()['windows'][0]['title'] == 'System — box'