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
fix(agent): tunnel reconcile fires on both transports (plan 77 A1)
Juan Denis99d1c86ebb55
diff --git a/backend/app/agent_gateway.py b/backend/app/agent_gateway.pyindex 99bd7ba2..e706e572 100644--- a/backend/app/agent_gateway.py+++ b/backend/app/agent_gateway.py@@ -297,26 +297,11 @@ class AgentNamespace(Namespace):})return+ # Capability side-effects (incl. the WireGuard tunnel reconcile)+ # happen inside update_capabilities so both transports — this WS+ # handler and the long-poll /poll body — share one ingest path.agent_registry.update_capabilities(agent.server_id, data or {})- # Panel-authoritative tunnel reconcile (#19): if this agent can- # drive WireGuard, re-apply (in the background) any tunnel config- # it participates in, so tunnels self-heal after an agent or panel- # restart. See docs/REMOTE_ACCESS_ROADMAP.md.- try:- caps = (data or {}).get('capabilities') or {}- if caps.get('wireguard'):- # TunnelBrokerService now lives in the serverkit-remote-access- # extension (plan 47); reach it only when installed, no-op otherwise.- from app.services.plugin_service import get_installed_extension_attr- TunnelBrokerService = get_installed_extension_attr(- 'serverkit-remote-access', 'tunnel_broker_service',- 'TunnelBrokerService')- if TunnelBrokerService is not None:- TunnelBrokerService.schedule_reconcile(agent.server_id)- except Exception:- logger.debug("tunnel reconcile scheduling skipped", exc_info=True)-def on_stream(self, data):"""Handle streaming data from agent (logs, metrics).diff --git a/backend/app/services/agent_registry.py b/backend/app/services/agent_registry.pyindex f30255e3..5461a855 100644--- a/backend/app/services/agent_registry.py+++ b/backend/app/services/agent_registry.py@@ -964,6 +964,31 @@ class AgentRegistry:sorted(k for k, v in clean_caps.items() if v),)+ self._schedule_tunnel_reconcile(server_id, clean_caps)++ def _schedule_tunnel_reconcile(self, server_id: str, caps: Dict[str, bool]):+ """Panel-authoritative tunnel reconcile (#19): if this agent can+ drive WireGuard, re-apply (in the background) any tunnel config it+ participates in, so tunnels self-heal after an agent or panel+ restart. Lives here — on the shared capability-ingest path — so it+ fires for BOTH transports (WS on_capabilities and the long-poll+ /poll body), not just WebSocket. See docs/REMOTE_ACCESS_ROADMAP.md.+ """+ if not caps.get('wireguard'):+ return+ try:+ # TunnelBrokerService lives in the serverkit-remote-access+ # extension (plan 47); reach it only when installed, no-op+ # otherwise.+ from app.services.plugin_service import get_installed_extension_attr+ TunnelBrokerService = get_installed_extension_attr(+ 'serverkit-remote-access', 'tunnel_broker_service',+ 'TunnelBrokerService')+ if TunnelBrokerService is not None:+ TunnelBrokerService.schedule_reconcile(server_id)+ except Exception:+ logger.debug("tunnel reconcile scheduling skipped", exc_info=True)+def get_capabilities(self, server_id: str) -> Optional[Dict[str, bool]]:"""Return the capability map for a connected agent, or None ifthe agent is not connected. Returns an empty dict if the agentdiff --git a/backend/tests/test_agent_poll_e2e.py b/backend/tests/test_agent_poll_e2e.pyindex 806cc17c..7783fd59 100644--- a/backend/tests/test_agent_poll_e2e.py+++ b/backend/tests/test_agent_poll_e2e.py@@ -233,3 +233,95 @@ def test_result_for_unknown_command_is_rejected(client, monkeypatch):res = client.post(RESULT, headers={"X-Session-Token": token},json={"command_id": "never-issued", "success": True})assert res.status_code == 404, res.get_data(as_text=True)+++# --------------------------------------------------------------------------+# Plan 77 A1 — capability side-effects are transport-neutral+# --------------------------------------------------------------------------++def _stub_tunnel_broker(monkeypatch):+ """Install a fake serverkit-remote-access TunnelBrokerService and return+ the list schedule_reconcile appends to."""+ calls = []++ class _FakeBroker:+ @staticmethod+ def schedule_reconcile(server_id):+ calls.append(server_id)++ import app.services.plugin_service as plugin_service++ real = plugin_service.get_installed_extension_attr++ def fake_get_attr(ext, module, attr):+ if (ext, module, attr) == (+ 'serverkit-remote-access', 'tunnel_broker_service', 'TunnelBrokerService'+ ):+ return _FakeBroker+ return real(ext, module, attr)++ monkeypatch.setattr(plugin_service, 'get_installed_extension_attr', fake_get_attr)+ return calls+++def test_poll_capabilities_trigger_tunnel_reconcile(app, client, monkeypatch):+ """A WireGuard-capable agent on the long-poll fallback transport must+ self-heal its tunnels exactly like one on WebSocket: the capability+ payload arriving via POST /poll schedules a tunnel reconcile.++ Regression for the plan-77 A1 bug: schedule_reconcile was only invoked+ from the WS on_capabilities handler, so poll-mode agents never healed."""+ server_id, agent_id, prefix, secret = _make_agent_server(monkeypatch)+ calls = _stub_tunnel_broker(monkeypatch)++ resp = client.post(CONNECT, json=_auth_payload(agent_id, prefix, secret))+ assert resp.status_code == 200+ token = resp.get_json()["session_token"]++ # Patch drain so the long-poll returns immediately.+ monkeypatch.setattr(agent_registry, "drain_outbound", lambda agent, max_wait_s=0: [])++ resp = client.post(+ POLL,+ headers={"X-Session-Token": token},+ json={+ "metrics": {"cpu_percent": 1.0},+ "capabilities": {+ "capabilities": {"docker": True, "wireguard": True},+ "platform": "linux",+ },+ },+ )+ assert resp.status_code == 200, resp.get_data(as_text=True)+ assert calls == [server_id]+++def test_ws_ingest_path_still_triggers_tunnel_reconcile(app, client, monkeypatch):+ """The WS handler delegates to the same registry ingest — a capability+ payload through update_capabilities (what on_capabilities calls)+ schedules the reconcile too, so the door is shared, not moved."""+ server_id, agent_id, prefix, secret = _make_agent_server(monkeypatch)+ calls = _stub_tunnel_broker(monkeypatch)++ resp = client.post(CONNECT, json=_auth_payload(agent_id, prefix, secret))+ assert resp.status_code == 200++ agent_registry.update_capabilities(+ server_id,+ {"capabilities": {"wireguard": True}, "platform": "linux"},+ )+ assert calls == [server_id]+++def test_non_wireguard_capabilities_do_not_reconcile(app, client, monkeypatch):+ """No wireguard capability -> no reconcile scheduling on either path."""+ server_id, agent_id, prefix, secret = _make_agent_server(monkeypatch)+ calls = _stub_tunnel_broker(monkeypatch)++ resp = client.post(CONNECT, json=_auth_payload(agent_id, prefix, secret))+ assert resp.status_code == 200++ agent_registry.update_capabilities(+ server_id, {"capabilities": {"docker": True}, "platform": "linux"}+ )+ assert calls == []