Agent Zero AI framework
refactor: Backend core rewrite - WsHandler + WsManager + handler migration
keyboardstaff1d81f72a3193
diff --git a/api/ws_dev_test.py b/api/ws_dev_test.pynew file mode 100644index 000000000..ab4f49ab8--- /dev/null+++ b/api/ws_dev_test.py@@ -0,0 +1,72 @@+import asyncio+from typing import Any++from helpers.ws import WsHandler+from helpers.print_style import PrintStyle+from helpers import runtime+++class WsDevTest(WsHandler):+ """Developer-only WebSocket test harness handler."""++ async def process(self, event: str, data: dict, sid: str) -> dict[str, Any] | None:+ if event == "ws_event_console_subscribe":+ if not runtime.is_development():+ return {"_error": True, "code": "NOT_AVAILABLE",+ "message": "Event console is available only in development mode"}+ registered = self.manager.register_diagnostic_watcher(self.namespace, sid)+ if not registered:+ return {"_error": True, "code": "SUBSCRIBE_FAILED",+ "message": "Unable to subscribe to diagnostics"}+ return {"status": "subscribed", "timestamp": data.get("requestedAt")}++ if event == "ws_event_console_unsubscribe":+ self.manager.unregister_diagnostic_watcher(self.namespace, sid)+ return {"status": "unsubscribed"}++ if event == "ws_tester_emit":+ message = data.get("message", "emit")+ payload = {"message": message, "echo": True, "timestamp": data.get("timestamp")}+ await self.broadcast("ws_tester_broadcast", payload)+ PrintStyle.info(f"Harness emit broadcasted message='{message}'")+ return None++ if event == "ws_tester_request":+ value = data.get("value")+ PrintStyle.debug("Harness request responded with echo %s", value)+ return {"echo": value, "handler": self.identifier, "status": "ok"}++ if event == "ws_tester_request_delayed":+ delay_ms = int(data.get("delay_ms", 0))+ await asyncio.sleep(delay_ms / 1000)+ PrintStyle.warning("Harness delayed request finished after %s ms", delay_ms)+ return {"status": "delayed", "delay_ms": delay_ms, "handler": self.identifier}++ if event == "ws_tester_trigger_persistence":+ phase = data.get("phase", "unknown")+ payload = {"phase": phase, "handler": self.identifier}+ await self.emit_to(sid, "ws_tester_persistence", payload)+ PrintStyle.info(f"Harness persistence event phase='{phase}' -> {sid}")+ return None++ if event == "ws_tester_broadcast_demo_trigger":+ payload = {"demo": True, "requested_at": data.get("requested_at")}+ await self.broadcast("ws_tester_broadcast_demo", payload)+ PrintStyle.info("Harness broadcast demo event dispatched")+ return None++ if event == "ws_tester_request_all":+ correlation_id = data.get("correlationId")+ aggregated = await self.dispatch_to_all_sids(+ "ws_tester_request",+ {"value": data.get("marker", "aggregate")},+ correlation_id=correlation_id,+ )+ return {"results": aggregated}++ # Ignore events not targeted at this handler (other activated handlers+ # may process them). Only warn for events that look like dev-harness+ # traffic so we don't spam logs with unrelated events.+ if event.startswith("ws_tester_"):+ PrintStyle.warning(f"Harness received unknown event '{event}'")+ return Nonediff --git a/api/ws_hello.py b/api/ws_hello.pynew file mode 100644index 000000000..117757fdd--- /dev/null+++ b/api/ws_hello.py@@ -0,0 +1,13 @@+from helpers.ws import WsHandler+from helpers.print_style import PrintStyle+++class WsHello(WsHandler):+ """Simple echo handler used for foundational testing."""++ async def process(self, event: str, data: dict, sid: str) -> dict | None:+ if event != "hello_request":+ return None+ name = data.get("name") or "stranger"+ PrintStyle.info(f"hello_request from {sid} ({name})")+ return {"message": f"Hello, {name}!", "handler": self.identifier}diff --git a/api/ws_webui.py b/api/ws_webui.pynew file mode 100644index 000000000..2fa9a9e42--- /dev/null+++ b/api/ws_webui.py@@ -0,0 +1,32 @@+from helpers.ws import WsHandler+from helpers import extension+++class WsWebui(WsHandler):+ """State synchronisation handler — the primary WebSocket endpoint for the UI."""++ async def on_connect(self, sid: str) -> None:+ await extension.call_extensions_async(+ "webui_ws_connect", agent=None, instance=self, sid=sid+ )++ async def on_disconnect(self, sid: str) -> None:+ await extension.call_extensions_async(+ "webui_ws_disconnect", agent=None, instance=self, sid=sid+ )++ async def process(self, event: str, data: dict, sid: str) -> dict | None:+ response_data: dict = {}++ await extension.call_extensions_async(+ "webui_ws_event",+ agent=None,+ instance=self,+ sid=sid,+ event_type=event,+ data=data,+ response_data=response_data,+ )++ # Return None (fire-and-forget) when no extension populated the response.+ return response_data if response_data else Nonediff --git a/helpers/api.py b/helpers/api.pyindex af767d18c..f3b031861 100644--- a/helpers/api.py+++ b/helpers/api.py@@ -1,11 +1,9 @@from abc import abstractmethodimport json-import socket-import structimport threadingfrom functools import wrapsfrom pathlib import Path-from typing import Union, TypedDict, Dict, Any+from typing import Union, Dict, Anyfrom flask import (Request,Response,@@ -19,7 +17,6 @@ from flask import ()from werkzeug.wrappers.response import Response as BaseResponsefrom agent import AgentContext-from initialize import initialize_agentfrom helpers.print_style import PrintStylefrom helpers.errors import format_errorfrom helpers import files, cache@@ -30,7 +27,7 @@ CACHE_AREA = "api_handlers(api)"cache.toggle_area(CACHE_AREA, False) # cache off for nowInput = dict-Output = Union[Dict[str, Any], Response, TypedDict] # type: ignore+Output = Union[Dict[str, Any], Response]class ApiHandler:@@ -99,59 +96,11 @@ class ApiHandler:# get context to run agent zero indef use_context(self, ctxid: str, create_if_not_exists: bool = True):- with self.thread_lock:- if not ctxid:- first = AgentContext.first()- if first:- AgentContext.use(first.id)- return first- context = AgentContext(config=initialize_agent(), set_current=True)- return context- got = AgentContext.use(ctxid)- if got:- return got- if create_if_not_exists:- context = AgentContext(- config=initialize_agent(), id=ctxid, set_current=True- )- return context- else:- raise Exception(f"Context {ctxid} not found")---def is_loopback_address(address: str) -> bool:- loopback_checker = {- socket.AF_INET: lambda x: (- struct.unpack("!I", socket.inet_aton(x))[0] >> (32 - 8)- )- == 127,- socket.AF_INET6: lambda x: x == "::1",- }- address_type = "hostname"- try:- socket.inet_pton(socket.AF_INET6, address)- address_type = "ipv6"- except socket.error:- try:- socket.inet_pton(socket.AF_INET, address)- address_type = "ipv4"- except socket.error:- address_type = "hostname"-- if address_type == "ipv4":- return loopback_checker[socket.AF_INET](address)- elif address_type == "ipv6":- return loopback_checker[socket.AF_INET6](address)- else:- for family in (socket.AF_INET, socket.AF_INET6):- try:- r = socket.getaddrinfo(address, None, family, socket.SOCK_STREAM)- except socket.gaierror:- return False- for family, _, _, _, sockaddr in r:- if not loopback_checker[family](sockaddr[0]):- return False- return True+ from helpers.context_utils import use_context as _use_context+ return _use_context(self.thread_lock, ctxid, create_if_not_exists)+++from helpers.network import is_loopback_addressdef requires_api_key(f):@@ -301,3 +250,20 @@ def register_watchdogs():patterns=["*.py"],handler=on_api_change,)++ # WS handler cache shares the same watched directories (api/, usr/api/)+ from helpers.ws import CACHE_AREA as WS_CACHE_AREA++ def on_ws_change(items: list[watchdog.WatchItem]):+ PrintStyle.debug("WS handler watchdog triggered:", items)+ cache.clear(WS_CACHE_AREA)++ watchdog.add_watchdog(+ "ws_handlers",+ roots=[+ files.get_abs_path(files.API_DIR),+ files.get_abs_path(files.USER_DIR, files.API_DIR),+ ],+ patterns=["ws_*.py"],+ handler=on_ws_change,+ )diff --git a/helpers/context_utils.py b/helpers/context_utils.pynew file mode 100644index 000000000..afa8dbccd--- /dev/null+++ b/helpers/context_utils.py@@ -0,0 +1,30 @@+"""Shared context helper used by both ApiHandler and WsHandler."""++import threading+from typing import Union++ThreadLockType = Union[threading.Lock, threading.RLock]+++def use_context(lock: ThreadLockType, ctxid: str, create_if_not_exists: bool = True):+ from agent import AgentContext+ from initialize import initialize_agent++ with lock:+ if not ctxid:+ first = AgentContext.first()+ if first:+ AgentContext.use(first.id)+ return first+ context = AgentContext(config=initialize_agent(), set_current=True)+ return context+ got = AgentContext.use(ctxid)+ if got:+ return got+ if create_if_not_exists:+ context = AgentContext(+ config=initialize_agent(), id=ctxid, set_current=True+ )+ return context+ else:+ raise Exception(f"Context {ctxid} not found")diff --git a/helpers/network.py b/helpers/network.pynew file mode 100644index 000000000..aa5a100b4--- /dev/null+++ b/helpers/network.py@@ -0,0 +1,31 @@+import socket+import struct+++def is_loopback_address(address: str) -> bool:+ """Check whether *address* resolves to a loopback interface."""+ _checkers = {+ socket.AF_INET: lambda x: (+ struct.unpack("!I", socket.inet_aton(x))[0] >> (32 - 8)+ ) == 127,+ socket.AF_INET6: lambda x: x == "::1",+ }+ try:+ socket.inet_pton(socket.AF_INET6, address)+ return _checkers[socket.AF_INET6](address)+ except socket.error:+ pass+ try:+ socket.inet_pton(socket.AF_INET, address)+ return _checkers[socket.AF_INET](address)+ except socket.error:+ pass+ for family in (socket.AF_INET, socket.AF_INET6):+ try:+ r = socket.getaddrinfo(address, None, family, socket.SOCK_STREAM)+ except socket.gaierror:+ return False+ for fam, _, _, _, sockaddr in r:+ if not _checkers[fam](sockaddr[0]):+ return False+ return Truediff --git a/helpers/plugins.py b/helpers/plugins.pyindex cfd64d133..0c8521468 100644--- a/helpers/plugins.py+++ b/helpers/plugins.py@@ -202,7 +202,7 @@ def clear_plugin_cache(plugin_names: list[str] | None = None):for area in areas:cache.clear(area)- from helpers.websocket_manager import send_data+ from helpers.ws_manager import send_dataDeferredTask().start_task(send_data,diff --git a/helpers/state_monitor.py b/helpers/state_monitor.pyindex ff4766125..bd21f2fc2 100644--- a/helpers/state_monitor.py+++ b/helpers/state_monitor.py@@ -14,10 +14,10 @@ from helpers.state_snapshot import (advance_state_request_after_snapshot,build_snapshot_from_request,)-from helpers.websocket import ConnectionNotFoundError+from helpers.ws import ConnectionNotFoundErrorif TYPE_CHECKING: # pragma: no cover - hints only- from helpers.websocket_manager import WebSocketManager+ from helpers.ws_manager import WsManagerConnectionIdentity = tuple[str, str] # (namespace, sid)@@ -60,12 +60,12 @@ class StateMonitor:self._projections: dict[ConnectionIdentity, ConnectionProjection] = {}self._debounce_handles: dict[ConnectionIdentity, asyncio.TimerHandle] = {}self._push_tasks: dict[ConnectionIdentity, asyncio.Task[None]] = {}- self._manager: WebSocketManager | None = None+ self._manager: WsManager | None = Noneself._emit_handler_id: str | None = Noneself._dispatcher_loop: asyncio.AbstractEventLoop | None = Noneself._dirty_wave_seq: int = 0- def bind_manager(self, manager: "WebSocketManager", *, handler_id: str | None = None) -> None:+ def bind_manager(self, manager: "WsManager", *, handler_id: str | None = None) -> None:with self._lock:self._manager = managerif handler_id:diff --git a/helpers/ws.py b/helpers/ws.pyindex 82c79d0a4..657a2c1a6 100644--- a/helpers/ws.py+++ b/helpers/ws.py@@ -1,22 +1,148 @@import threading+import uuidfrom abc import abstractmethodfrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, Union+from typing import Any, Iterable, Union, TYPE_CHECKING+from urllib.parse import urlparseimport socketiofrom flask import Flask, session, request-from agent import AgentContext-from initialize import initialize_agentfrom helpers import files, cache-from helpers.api import is_loopback_addressfrom helpers.print_style import PrintStylefrom helpers.errors import format_error-from helpers.websocket import validate_ws_origin++if TYPE_CHECKING:+ from helpers.ws_manager import WsManager+++# Utilities++from helpers.network import is_loopback_address+++class ConnectionNotFoundError(RuntimeError):+ """Raised when attempting to emit to a non-existent WebSocket connection."""++ def __init__(self, sid: str, *, namespace: str | None = None) -> None:+ self.sid = sid+ self.namespace = namespace+ if namespace:+ super().__init__(f"Connection not found: namespace={namespace} sid={sid}")+ else:+ super().__init__(f"Connection not found: {sid}")+++def _default_port_for_scheme(scheme: str) -> int | None:+ if scheme == "http":+ return 80+ if scheme == "https":+ return 443+ return None+++def normalize_origin(value: Any) -> str | None:+ """Normalize an Origin/Referer header value to scheme://host[:port]."""+ if not isinstance(value, str) or not value.strip():+ return None+ parsed = urlparse(value.strip())+ if not parsed.scheme or not parsed.hostname:+ return None+ origin = f"{parsed.scheme}://{parsed.hostname}"+ if parsed.port:+ origin += f":{parsed.port}"+ return origin+++def _parse_host_header(value: Any) -> tuple[str | None, int | None]:+ if not isinstance(value, str) or not value.strip():+ return None, None+ parsed = urlparse(f"http://{value.strip()}")+ return parsed.hostname, parsed.port+++def validate_ws_origin(environ: dict[str, Any]) -> tuple[bool, str | None]:+ """Validate the browser Origin during the Socket.IO handshake.++ This is the minimum baseline recommended by RFC 6455 (Origin considerations)+ and OWASP (CSWSH mitigation): reject cross-origin WebSocket handshakes when+ the server is intended for a specific web UI origin.+ """++ raw_origin = environ.get("HTTP_ORIGIN") or environ.get("HTTP_REFERER")+ origin = normalize_origin(raw_origin)+ if origin is None:+ return False, "missing_origin"++ origin_parsed = urlparse(origin)+ origin_host = origin_parsed.hostname.lower() if origin_parsed.hostname else None+ origin_port = origin_parsed.port or _default_port_for_scheme(origin_parsed.scheme)+ if origin_host is None or origin_port is None:+ return False, "invalid_origin"++ raw_host = environ.get("HTTP_HOST")+ req_host, req_port = _parse_host_header(raw_host)+ if not req_host:+ req_host = environ.get("SERVER_NAME")++ if req_port is None:+ server_port_raw = environ.get("SERVER_PORT")+ try:+ server_port = int(server_port_raw) if server_port_raw is not None else None+ except (TypeError, ValueError):+ server_port = None+ if server_port is not None and server_port > 0:+ req_port = server_port++ if req_host:+ req_host = req_host.lower()+ if req_port is None:+ req_port = origin_port++ forwarded_host_raw = environ.get("HTTP_X_FORWARDED_HOST")+ forwarded_host = None+ forwarded_port = None+ if isinstance(forwarded_host_raw, str) and forwarded_host_raw.strip():+ first = forwarded_host_raw.split(",")[0].strip()+ forwarded_host, forwarded_port = _parse_host_header(first)+ if forwarded_host:+ forwarded_host = forwarded_host.lower()++ forwarded_proto_raw = environ.get("HTTP_X_FORWARDED_PROTO")+ forwarded_scheme = None+ if isinstance(forwarded_proto_raw, str) and forwarded_proto_raw.strip():+ forwarded_scheme = forwarded_proto_raw.split(",")[0].strip().lower()+ forwarded_scheme = forwarded_scheme or origin_parsed.scheme+ forwarded_port = (+ forwarded_port+ if forwarded_port is not None+ else _default_port_for_scheme(forwarded_scheme) or origin_port+ )++ candidates: list[tuple[str, int]] = []+ if req_host:+ candidates.append((req_host, int(req_port)))+ if forwarded_host:+ candidates.append((forwarded_host, int(forwarded_port)))++ if not candidates:+ return False, "missing_host"++ for host, port in candidates:+ if origin_host == host and origin_port == port:+ return True, None++ if origin_host not in {host for host, _ in candidates}:+ return False, "origin_host_mismatch"+ return False, "origin_port_mismatch"+++# ConstantsThreadLockType = Union[threading.Lock, threading.RLock]+NAMESPACE = "/ws"CACHE_AREA = "ws_handlers(api)(plugins)"cache.toggle_area(CACHE_AREA, False) # cache off for now@@ -37,9 +163,52 @@ _contexts_lock = threading.Lock()class WsHandler:- def __init__(self, socketio_server: socketio.AsyncServer, lock: ThreadLockType):+ """Base class for WebSocket handlers loaded from api/ directories.++ Mirrors ApiHandler conventions: declarative security flags, dynamic file-+ based loading, and a ``process(event, data, sid)`` entry point. Handlers+ are activated per-connection based on the ``auth.handlers`` list sent by the+ client during the Socket.IO connect handshake.+ """++ def __init__(+ self,+ socketio_server: socketio.AsyncServer,+ lock: ThreadLockType,+ *,+ manager: "WsManager | None" = None,+ namespace: str = NAMESPACE,+ ):self.socketio = socketio_serverself.lock = lock+ self._manager = manager+ self._namespace = namespace++ # Properties++ @property+ def namespace(self) -> str:+ return self._namespace++ @property+ def manager(self) -> "WsManager":+ if self._manager is None:+ raise RuntimeError("WsHandler has no WsManager bound")+ return self._manager++ @property+ def identifier(self) -> str:+ return f"{self.__class__.__module__}.{self.__class__.__name__}"++ def bind_manager(+ self, manager: "WsManager", *, namespace: str | None = None+ ) -> None:+ """Late-bind (or rebind) the manager and optionally the namespace."""+ self._manager = manager+ if namespace is not None:+ self._namespace = namespace++ # Security flags (mirror ApiHandler)@classmethoddef requires_loopback(cls) -> bool:@@ -57,67 +226,164 @@ class WsHandler:def requires_csrf(cls) -> bool:return cls.requires_auth()- @abstractmethod- async def process(self, data: dict, sid: str) -> dict | None:- pass+ # Lifecycle hooks- async def on_connect(self, sid: str) -> dict | None:- return None+ async def on_connect(self, sid: str) -> None:+ passasync def on_disconnect(self, sid: str) -> None:pass+ # Event processing++ @abstractmethod+ async def process(self, event: str, data: dict, sid: str) -> dict | None:+ """Handle an incoming event.++ Return a dict to include in the acknowledgement, or ``None`` for+ fire-and-forget semantics.+ """++ # Emit helpers (delegate to WsManager for envelope wrapping)++ async def emit_to(+ self,+ sid: str,+ event: str,+ data: dict,+ *,+ correlation_id: str | None = None,+ ) -> None:+ await self.manager.emit_to(+ self._namespace, sid, event, data,+ handler_id=self.identifier,+ correlation_id=correlation_id,+ )++ async def broadcast(+ self,+ event: str,+ data: dict,+ *,+ exclude_sids: str | Iterable[str] | None = None,+ correlation_id: str | None = None,+ ) -> None:+ await self.manager.broadcast(+ self._namespace, event, data,+ exclude_sids=exclude_sids,+ handler_id=self.identifier,+ correlation_id=correlation_id,+ )++ # Aggregation helper++ async def dispatch_to_all_sids(+ self,+ event: str,+ data: dict,+ *,+ correlation_id: str | None = None,+ ) -> list[dict[str, Any]]:+ """Dispatch *event* to every connected sid's activated handlers and+ aggregate the results.++ Returns a list of ``{sid, correlationId, results}`` dicts – one per+ connected sid. This mirrors the shape produced by+ ``WsManager.route_event_all`` so that existing frontend+ assertions remain valid.+ """+ cid = correlation_id or uuid.uuid4().hex++ with _contexts_lock:+ snapshot = {+ sid: dict(handlers)+ for sid, handlers in _active_handlers.items()+ }++ aggregated: list[dict[str, Any]] = []+ for sid, handlers in snapshot.items():+ ctx = _ws_contexts.get(sid)+ sid_results: list[dict[str, Any]] = []+ for _path, instance in handlers.items():+ if ctx is not None:+ error = _check_security(type(instance), ctx)+ if error is not None:+ sid_results.append({+ "handlerId": instance.identifier,+ "ok": False,+ "correlationId": cid,+ "error": error,+ })+ continue+ try:+ result = await instance.process(event, dict(data, correlationId=cid), sid)+ if result is not None:+ sid_results.append({+ "handlerId": instance.identifier,+ "ok": True,+ "correlationId": cid,+ "data": result,+ })+ except Exception as e:+ sid_results.append({+ "handlerId": instance.identifier,+ "ok": False,+ "correlationId": cid,+ "error": {"code": "HANDLER_ERROR", "error": str(e)},+ })+ aggregated.append({+ "sid": sid,+ "correlationId": cid,+ "results": sid_results,+ })+ return aggregated++ # Context helper (shared with ApiHandler)+def use_context(self, ctxid: str, create_if_not_exists: bool = True):- with self.lock:- if not ctxid:- first = AgentContext.first()- if first:- AgentContext.use(first.id)- return first- context = AgentContext(config=initialize_agent(), set_current=True)- return context- got = AgentContext.use(ctxid)- if got:- return got- if create_if_not_exists:- context = AgentContext(config=initialize_agent(), id=ctxid, set_current=True)- return context- else:- raise Exception(f"Context {ctxid} not found")+ from helpers.context_utils import use_context as _use_context+ return _use_context(self.lock, ctxid, create_if_not_exists)++# Security check (aligned with api.py decorators)def _check_security(handler_cls: type[WsHandler], ctx: _SecurityContext) -> dict[str, Any] | None:+ """Return an error payload dict if the check fails, or ``None`` on success."""+if handler_cls.requires_loopback():if not ctx.remote_addr or not is_loopback_address(ctx.remote_addr):- return {"ok": False, "error": "Access denied", "code": 403}+ return {"code": "FORBIDDEN", "error": "Access denied"}if handler_cls.requires_auth():from helpers import loginuser_pass_hash = login.get_credentials_hash()if user_pass_hash and ctx.auth_hash != user_pass_hash:- return {"ok": False, "error": "Authentication required", "code": 401}+ return {"code": "AUTH_REQUIRED", "error": "Authentication required"}if handler_cls.requires_csrf():if not ctx.csrf_token:- return {"ok": False, "error": "CSRF token not initialised", "code": 403}+ return {"code": "CSRF_MISSING", "error": "CSRF token not initialised"}if not ctx.client_csrf_token or ctx.client_csrf_token != ctx.csrf_token:- return {"ok": False, "error": "CSRF token missing or invalid", "code": 403}+ return {"code": "CSRF_INVALID", "error": "CSRF token missing or invalid"}if ctx.csrf_cookie != ctx.csrf_token:- return {"ok": False, "error": "CSRF cookie mismatch", "code": 403}+ return {"code": "CSRF_COOKIE", "error": "CSRF cookie mismatch"}if handler_cls.requires_api_key():from helpers.settings import get_settingsvalid_key = get_settings().get("mcp_server_token")if not ctx.api_key or ctx.api_key != valid_key:- return {"ok": False, "error": "API key required", "code": 401}+ return {"code": "API_KEY_REQUIRED", "error": "API key required"}return None+# Namespace registration+def register_ws_namespace(socketio_server: socketio.AsyncServer,webapp: Flask,lock: ThreadLockType,+ manager: "WsManager | None" = None,) -> None:from helpers.modules import load_classes_from_filefrom helpers import plugins, runtime@@ -132,6 +398,14 @@ def register_ws_namespace(if classes:handler_cls = classes[0]+ # Check user api/<path>.py+ if handler_cls is None:+ user_file = files.get_abs_path(files.USER_DIR, f"api/{path}.py")+ if files.exists(user_file):+ classes = load_classes_from_file(user_file, WsHandler)+ if classes:+ handler_cls = classes[0]+# Check plugin api/<handler>.py — path format: plugins/<plugin_name>/<handler>if handler_cls is None and path.startswith("plugins/"):parts = path.split("/", 2)@@ -156,13 +430,13 @@ def register_ws_namespace(cache.add(CACHE_AREA, path, handler_cls)return handler_cls- @socketio_server.on("connect", namespace="/ws") # type: ignore+ @socketio_server.on("connect", namespace=NAMESPACE) # type: ignoreasync def _on_connect(sid, environ, auth):with webapp.request_context(environ):origin_ok, origin_reason = validate_ws_origin(environ)if not origin_ok:PrintStyle.warning(- f"WS /ws connect rejected for {sid}: {origin_reason or 'invalid'}"+ f"WS connect rejected for {sid}: {origin_reason or 'invalid'}")return False@@ -182,11 +456,19 @@ def register_ws_namespace(if isinstance(auth, dict) else None),)+ user_id = session.get("user_id") or "single_user"+with _contexts_lock:_ws_contexts[sid] = ctx+ # Register with WsManager first so that the dispatcher loop and+ # connection tracking are available before handler on_connect runs+ # (extensions like StateSync depend on manager._dispatcher_loop).+ if manager is not None:+ await manager.handle_connect(NAMESPACE, sid, user_id=user_id)+# Activate handlers declared in auth.handlers- handler_paths = []+ handler_paths: list[str] = []if isinstance(auth, dict):raw = auth.get("handlers")if isinstance(raw, list):@@ -201,7 +483,10 @@ def register_ws_namespace(error = _check_security(handler_cls, ctx)if error is not None:continue- instance = handler_cls(socketio_server, lock)+ instance = handler_cls(+ socketio_server, lock,+ manager=manager, namespace=NAMESPACE,+ )await instance.on_connect(sid)activated[path] = instanceexcept Exception as e:@@ -212,7 +497,7 @@ def register_ws_namespace(return True- @socketio_server.on("disconnect", namespace="/ws") # type: ignore+ @socketio_server.on("disconnect", namespace=NAMESPACE) # type: ignoreasync def _on_disconnect(sid):with _contexts_lock:activated = _active_handlers.pop(sid, {})@@ -224,31 +509,83 @@ def register_ws_namespace(except Exception as e:PrintStyle.error(f"WS on_disconnect error ({path}): {format_error(e)}")- @socketio_server.on("*", namespace="/ws") # type: ignore+ if manager is not None:+ await manager.handle_disconnect(NAMESPACE, sid)++ @socketio_server.on("*", namespace=NAMESPACE) # type: ignoreasync def _dispatch(event, sid, data):- path = event- payload = data if isinstance(data, dict) else {}+ incoming = data if isinstance(data, dict) else {}try:with _contexts_lock:ctx = _ws_contexts.get(sid)- activated = _active_handlers.get(sid, {})- if ctx is None:- return {"ok": False, "error": "No security context", "code": 401}+ activated = dict(_active_handlers.get(sid, {}))- instance = activated.get(path)- if instance is None:- return {"ok": False, "error": f"WS endpoint not activated: {path}", "code": 404}+ correlation_id = incoming.get("correlationId") or uuid.uuid4().hex- # Security check- error = _check_security(type(instance), ctx)- if error is not None:- return error+ if ctx is None:+ return _error_response("AUTH_REQUIRED",+ "No security context", correlation_id)+ if not activated:+ return _error_response("NO_HANDLERS",+ "No handlers activated", correlation_id)++ # Unwrap nested payload (mirrors WsManager.route_event):+ # frontend sends {ts, data: {actual fields...}, correlationId}+ if "data" in incoming and isinstance(incoming.get("data"), dict):+ handler_payload = dict(incoming["data"])+ else:+ handler_payload = dict(incoming)+ handler_payload["correlationId"] = correlation_id- # Use cached instance and process- return await instance.process(payload, sid)+ results: list[dict[str, Any]] = []+ for path, instance in activated.items():+ error = _check_security(type(instance), ctx)+ if error is not None:+ results.append({+ "handlerId": instance.identifier,+ "ok": False,+ "correlationId": correlation_id,+ "error": error,+ })+ continue+ try:+ result = await instance.process(event, handler_payload, sid)+ if result is not None:+ results.append({+ "handlerId": instance.identifier,+ "ok": True,+ "correlationId": correlation_id,+ "data": result,+ })+ except Exception as e:+ error_text = format_error(e)+ PrintStyle.error(f"WS handler error ({path}/{event}): {error_text}")+ results.append({+ "handlerId": instance.identifier,+ "ok": False,+ "correlationId": correlation_id,+ "error": {"code": "HANDLER_ERROR", "error": "Internal server error"},+ })++ return {"correlationId": correlation_id, "results": results}except Exception as e:error_text = format_error(e)- PrintStyle.error(f"WS handler error ({path}): {error_text}")- return {"ok": False, "error": error_text, "code": 500}\ No newline at end of file+ PrintStyle.error(f"WS dispatch error ({event}): {error_text}")+ return _error_response(+ "INTERNAL_ERROR", "Internal server error",+ incoming.get("correlationId", ""),+ )+++def _error_response(code: str, message: str,+ correlation_id: str) -> dict[str, Any]:+ return {+ "correlationId": correlation_id,+ "results": [{+ "handlerId": "ws.dispatch",+ "ok": False,+ "error": {"code": code, "error": message},+ }],+ }\ No newline at end of filediff --git a/helpers/ws_manager.py b/helpers/ws_manager.pynew file mode 100644index 000000000..95ea587c0--- /dev/null+++ b/helpers/ws_manager.py@@ -0,0 +1,1351 @@+from __future__ import annotations++import asyncio, os+import re+import time+import threading+from collections import defaultdict, deque+from dataclasses import dataclass, field+from datetime import datetime, timedelta, timezone+from typing import Any, Callable, Deque, Dict, Iterable, List, Optional, Set++import socketio+import uuid++from helpers.defer import DeferredTask+from helpers.print_style import PrintStyle+from helpers import runtime+from helpers.ws import ConnectionNotFoundError, WsHandler+++def _ws_debug_enabled() -> bool:+ """Check A0_WS_DEBUG env var — no heavyweight imports needed."""+ value = os.getenv("A0_WS_DEBUG", "").strip().lower()+ return value in {"1", "true", "yes", "on"}+++# Event validation++_EVENT_NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_]*$")+_RESERVED_EVENT_NAMES: set[str] = {+ "connect",+ "disconnect",+ "error",+ "ping",+ "pong",+ "connect_error",+ "reconnect",+ "reconnect_attempt",+ "reconnect_error",+ "reconnect_failed",+}+++# WsResult – standardized handler return value++class WsResult:+ """Helper wrapper for standardized handler results.++ Instances are converted to the canonical ``RequestResultItem`` shape by+ :class:`WsManager`. Helper constructors enforce payload validation+ so handlers no longer need to hand-craft dictionaries.+ """++ __slots__ = ("_ok", "_data", "_error", "_correlation_id", "_duration_ms")++ def __init__(+ self,+ ok: bool,+ data: dict[str, Any] | None = None,+ error: dict[str, Any] | None = None,+ correlation_id: str | None = None,+ duration_ms: float | None = None,+ ) -> None:+ if ok and error:+ raise ValueError("Cannot be both ok and have an error")+ if not ok and not error:+ raise ValueError("Must either be ok or have an error")+ if data is not None and not isinstance(data, dict):+ raise TypeError("Data payload must be a dictionary or None")+ if error is not None and not isinstance(error, dict):+ raise TypeError("Error payload must be a dictionary or None")+ if correlation_id is not None and not isinstance(correlation_id, str):+ raise TypeError("Correlation ID must be a string or None")+ if duration_ms is not None and not isinstance(duration_ms, (int, float)):+ raise TypeError("Duration must be a number or None")++ self._ok = bool(ok)+ self._data = dict(data) if data is not None else None+ self._error = dict(error) if error is not None else None+ self._correlation_id = correlation_id+ self._duration_ms = float(duration_ms) if duration_ms is not None else None++ @classmethod+ def ok(+ cls,+ data: dict[str, Any] | None = None,+ *,+ correlation_id: str | None = None,+ duration_ms: float | None = None,+ ) -> "WsResult":+ if data is not None and not isinstance(data, dict):+ raise TypeError("WsResult.ok data must be a dict or None")+ payload = dict(data) if data is not None else None+ return cls(+ ok=True,+ data=payload,+ correlation_id=correlation_id,+ duration_ms=duration_ms,+ )++ @classmethod+ def error(+ cls,+ *,+ code: str,+ message: str,+ details: Any | None = None,+ correlation_id: str | None = None,+ duration_ms: float | None = None,+ ) -> "WsResult":+ if not isinstance(code, str) or not code.strip():+ raise ValueError("Error code must be a non-empty string")+ if not isinstance(message, str) or not message.strip():+ raise ValueError("Error message must be a non-empty string")++ error_payload: dict[str, Any] = {"code": code, "error": message}+ if details is not None:+ error_payload["details"] = details+ return cls(+ ok=False,+ error=error_payload,+ correlation_id=correlation_id,+ duration_ms=duration_ms,+ )++ def as_result(+ self,+ *,+ handler_id: str,+ fallback_correlation_id: str | None,+ duration_ms: float | None = None,+ ) -> dict[str, Any]:+ result: dict[str, Any] = {+ "handlerId": handler_id,+ "ok": self._ok,+ }++ effective_duration = (+ self._duration_ms if self._duration_ms is not None else duration_ms+ )+ if effective_duration is not None:+ result["durationMs"] = round(effective_duration, 4)++ correlation = (+ self._correlation_id+ if self._correlation_id is not None+ else fallback_correlation_id+ )+ if correlation is not None:+ result["correlationId"] = correlation++ if self._ok:+ result["data"] = dict(self._data) if self._data is not None else {}+ else:+ result["error"] = dict(self._error) if self._error is not None else {+ "code": "INTERNAL_ERROR",+ "error": "Internal server error",+ }+ return result+++def validate_event_type(event_type: str) -> str:+ """Validate an event name: must be lowercase_snake_case and not reserved."""+ if not isinstance(event_type, str):+ raise TypeError("Event type must be a string")+ if not _EVENT_NAME_PATTERN.fullmatch(event_type):+ raise ValueError(+ f"Invalid event type '{event_type}' – must match lowercase_snake_case"+ )+ if event_type in _RESERVED_EVENT_NAMES:+ raise ValueError(+ f"Event type '{event_type}' is reserved by Socket.IO and cannot be used"+ )+ return event_type+++BUFFER_MAX_SIZE = 100+BUFFER_TTL = timedelta(hours=1)+_shared_ws_manager: WsManager | None = None+++async def send_data(+ event_type: str,+ data: dict[str, Any],+ endpoint_name: str = "/ws",+ connection_id: str | None = None,+) -> None:+ manager = get_shared_ws_manager()+ await manager.send_data(endpoint_name, event_type, data, connection_id)+++def _utcnow() -> datetime:+ return datetime.now(timezone.utc)+++def set_shared_ws_manager(manager: "WsManager") -> None:+ global _shared_ws_manager+ _shared_ws_manager = manager+++def get_shared_ws_manager() -> "WsManager":+ manager = _shared_ws_manager+ if manager is None:+ raise RuntimeError("Shared WsManager has not been initialized")+ return manager+++@dataclass+class BufferedEvent:+ event_type: str+ data: dict[str, Any]+ handler_id: str | None = None+ correlation_id: str | None = None+ timestamp: datetime = field(default_factory=_utcnow)+++@dataclass+class ConnectionInfo:+ namespace: str+ sid: str+ connected_at: datetime = field(default_factory=_utcnow)+ last_activity: datetime = field(default_factory=_utcnow)+++ConnectionIdentity = tuple[str, str] # (namespace, sid)+++@dataclass+class _HandlerExecution:+ handler: WsHandler+ value: Any+ duration_ms: float | None+++DIAGNOSTIC_EVENT = "ws_dev_console_event"+LIFECYCLE_CONNECT_EVENT = "ws_lifecycle_connect"+LIFECYCLE_DISCONNECT_EVENT = "ws_lifecycle_disconnect"+++class WsManager:+ def __init__(self, socketio: socketio.AsyncServer, lock) -> None:+ self.socketio = socketio+ self.lock = lock+ self.handlers: defaultdict[str, List[WsHandler]] = defaultdict(list)+ self.connections: Dict[ConnectionIdentity, ConnectionInfo] = {}+ self.buffers: defaultdict[ConnectionIdentity, Deque[BufferedEvent]] = (+ defaultdict(deque)+ )+ self._known_sids: Set[ConnectionIdentity] = set()+ self._identifier: str = f"{self.__class__.__module__}.{self.__class__.__name__}"+ # Session tracking (single-user default)+ self.user_to_sids: defaultdict[str, Set[ConnectionIdentity]] = defaultdict(set)+ self.sid_to_user: Dict[ConnectionIdentity, str | None] = {}+ self._ALL_USERS_BUCKET = "allUsers"+ self._server_restart_enabled: bool = False+ self._diagnostic_watchers: Set[ConnectionIdentity] = set()+ self._diagnostics_enabled: bool = runtime.is_development()+ self._dispatcher_loop: asyncio.AbstractEventLoop | None = None+ self._handler_worker: DeferredTask | None = None++ # Internal: development-only debug logging to avoid noise in production+ def _debug(self, message: str) -> None:+ if _ws_debug_enabled():+ PrintStyle.debug(message)++ def _ensure_dispatcher_loop(self) -> None:+ if self._dispatcher_loop is None:+ try:+ self._dispatcher_loop = asyncio.get_running_loop()+ except RuntimeError:+ return++ def _get_handler_worker(self) -> DeferredTask:+ if self._handler_worker is None:+ self._handler_worker = DeferredTask(thread_name="WsHandlers")+ return self._handler_worker++ async def _run_on_dispatcher_loop(self, coro: Any) -> Any:+ self._ensure_dispatcher_loop()+ dispatcher_loop = self._dispatcher_loop+ if dispatcher_loop is None:+ return await coro+ if dispatcher_loop.is_closed():+ try:+ coro.close()+ except Exception: # pragma: no cover - best-effort cleanup+ pass+ raise RuntimeError("Dispatcher event loop is closed")++ try:+ running_loop = asyncio.get_running_loop()+ except RuntimeError:+ running_loop = None++ if running_loop is dispatcher_loop:+ return await coro++ future = asyncio.run_coroutine_threadsafe(coro, dispatcher_loop)+ return await asyncio.wrap_future(future)++ def _diagnostics_active(self) -> bool:+ if not self._diagnostics_enabled:+ return False+ with self.lock:+ return bool(self._diagnostic_watchers)++ def _copy_diagnostic_watchers(self) -> list[ConnectionIdentity]:+ with self.lock:+ return list(self._diagnostic_watchers)++ def register_diagnostic_watcher(self, namespace: str, sid: str) -> bool:+ if not self._diagnostics_enabled:+ return False+ identity: ConnectionIdentity = (namespace, sid)+ with self.lock:+ if identity not in self.connections:+ return False+ self._diagnostic_watchers.add(identity)+ return True++ def unregister_diagnostic_watcher(self, namespace: str, sid: str) -> None:+ identity: ConnectionIdentity = (namespace, sid)+ with self.lock:+ self._diagnostic_watchers.discard(identity)++ def _timestamp(self) -> str:+ return _utcnow().isoformat(timespec="milliseconds").replace("+00:00", "Z")++ def _summarize_payload(self, payload: dict[str, Any] | None) -> dict[str, Any]:+ if not isinstance(payload, dict):+ return {}+ summary: dict[str, Any] = {}+ for key in list(payload.keys())[:5]:+ value = payload[key]+ if isinstance(value, (str, int, float, bool)) or value is None:+ preview = value+ elif isinstance(value, dict):+ preview = f"dict({len(value)})"+ elif isinstance(value, list):+ preview = f"list({len(value)})"+ else:+ preview = value.__class__.__name__+ summary[key] = preview+ summary["__sizeBytes__"] = len(str(payload).encode("utf-8"))+ return summary++ def _summarize_results(self, results: List[dict[str, Any]]) -> dict[str, Any]:+ summary = {"ok": 0, "error": 0, "handlers": []}+ for result in results:+ handler_id = result.get("handlerId")+ ok = bool(result.get("ok"))+ if ok:+ summary["ok"] += 1+ else:+ summary["error"] += 1+ summary["handlers"].append(+ {+ "handlerId": handler_id,+ "ok": ok,+ "errorCode": (result.get("error") or {}).get("code"),+ "durationMs": result.get("durationMs"),+ }+ )+ summary["handlerCount"] = len(summary["handlers"])+ return summary++ async def _publish_diagnostic_event(+ self, payload: dict[str, Any] | Callable[[], dict[str, Any]]+ ) -> None:+ if not self._diagnostics_enabled:+ return+ watchers = self._copy_diagnostic_watchers()+ if not watchers:+ return+ effective_payload = payload() if callable(payload) else payload+ if (+ isinstance(effective_payload, dict)+ and "sourceNamespace" not in effective_payload+ ):+ origin = effective_payload.get("namespace")+ if isinstance(origin, str) and origin.strip():+ effective_payload = {+ **effective_payload,+ "sourceNamespace": origin.strip(),+ }++ async def _emit_to_watcher(identity: ConnectionIdentity) -> None:+ namespace, sid = identity+ try:+ await self.emit_to(+ namespace,+ sid,+ DIAGNOSTIC_EVENT,+ effective_payload,+ handler_id=self._identifier,+ diagnostic=True,+ )+ except ConnectionNotFoundError:+ self.unregister_diagnostic_watcher(namespace, sid)++ await asyncio.gather(*(_emit_to_watcher(identity) for identity in watchers))++ def _schedule_lifecycle_broadcast(+ self, namespace: str, event_type: str, payload: dict[str, Any]+ ) -> None:+ async def _broadcast() -> None:+ try:+ await self.broadcast(+ namespace,+ event_type,+ payload,+ diagnostic=True,+ )+ except Exception as exc: # pragma: no cover - diagnostic+ self._debug(f"Failed to broadcast lifecycle event {event_type}: {exc}")++ asyncio.create_task(_broadcast())++ def _normalize_handler_filter(self, value: Any, field_name: str) -> Set[str] | None:+ if value is None:+ return None+ if isinstance(value, str):+ return {value}+ try:+ iterator = iter(value)+ except TypeError as exc: # pragma: no cover - defensive+ raise ValueError(+ f"{field_name} must be an array of handler identifiers"+ ) from exc++ normalized: Set[str] = set()+ for item in iterator:+ if not isinstance(item, str):+ raise ValueError(+ f"{field_name} values must be handler identifier strings"+ )+ normalized.add(item)+ return normalized++ def _normalize_sid_filter(self, value: str | Iterable[str] | None) -> Set[str]:+ if value is None:+ return set()+ if isinstance(value, str):+ return {value}+ normalized: Set[str] = set()+ for item in value:+ normalized.add(str(item))+ return normalized++ def _select_handlers(+ self,+ namespace: str,+ *,+ include: Set[str] | None,+ exclude: Set[str] | None,+ ) -> tuple[list[WsHandler], Set[str]]:+ registered = self.handlers.get(namespace, [])+ available_ids = {handler.identifier for handler in registered}++ if include is not None:+ unknown = include - available_ids+ if unknown:+ raise ValueError(+ f"Unknown handler(s) in includeHandlers for namespace '{namespace}': "+ f"{', '.join(sorted(unknown))}"+ )+ if exclude is not None:+ unknown = exclude - available_ids+ if unknown:+ raise ValueError(+ f"Unknown handler(s) in excludeHandlers for namespace '{namespace}': "+ f"{', '.join(sorted(unknown))}"+ )++ selected: list[WsHandler] = []+ for handler in registered:+ ident = handler.identifier+ if include is not None and ident not in include:+ continue+ if exclude is not None and ident in exclude:+ continue+ selected.append(handler)++ return selected, available_ids++ def _resolve_correlation_id(self, payload: dict[str, Any]) -> str:+ value = payload.get("correlationId")+ if isinstance(value, str) and value.strip():+ correlation_id = value.strip()+ else:+ correlation_id = uuid.uuid4().hex+ payload["correlationId"] = correlation_id+ return correlation_id++ def register_handlers(+ self, handlers_by_namespace: dict[str, Iterable[WsHandler]]+ ) -> None:+ for namespace, handlers in handlers_by_namespace.items():+ for handler in handlers:+ handler.bind_manager(self, namespace=namespace)+ if _ws_debug_enabled():+ PrintStyle.info(+ "Registered WebSocket handler %s namespace=%s"+ % (handler.identifier, namespace)+ )+ existing = self.handlers.get(namespace, [])+ if handler in existing:+ PrintStyle.warning(+ f"Duplicate handler registration for namespace '{namespace}'"+ )+ self.handlers[namespace].append(handler)+ self._debug(+ f"Registered handler {handler.identifier} namespace={namespace}"+ )++ def iter_event_types(self, namespace: str) -> Iterable[str]:+ return []++ def iter_namespaces(self) -> list[str]:+ return list(self.handlers.keys())++ async def _invoke_handler(+ self,+ handler: WsHandler,+ event_type: str,+ payload: dict[str, Any],+ sid: str,+ ) -> _HandlerExecution:+ instrument = self._diagnostics_active()+ start = time.perf_counter() if instrument else None+ try:+ value = await self._get_handler_worker().execute_inside(+ handler.process, event_type, payload, sid+ )+ except Exception as exc: # pragma: no cover - handled by caller+ duration_ms = (+ (time.perf_counter() - start) * 1000 if start is not None else None+ )+ return _HandlerExecution(handler, exc, duration_ms)+ duration_ms = (+ (time.perf_counter() - start) * 1000 if start is not None else None+ )+ return _HandlerExecution(handler, value, duration_ms)++ async def handle_connect(+ self, namespace: str, sid: str, user_id: str | None = None+ ) -> None:+ self._ensure_dispatcher_loop()+ user_bucket = user_id or "single_user"+ identity: ConnectionIdentity = (namespace, sid)+ with self.lock:+ self.connections[identity] = ConnectionInfo(namespace=namespace, sid=sid)+ self._known_sids.add(identity)+ self.sid_to_user[identity] = user_bucket+ self.user_to_sids[self._ALL_USERS_BUCKET].add(identity)+ self.user_to_sids[user_bucket].add(identity)+ connection_count = sum(+ 1 for conn_identity in self.connections if conn_identity[0] == namespace+ )+ if _ws_debug_enabled():+ PrintStyle.info(f"WebSocket connected: namespace={namespace} sid={sid}")+ await self._run_lifecycle(namespace, lambda h: h.on_connect(sid))+ await self._flush_buffer(identity)+ if self._server_restart_enabled:+ await self.emit_to(+ namespace,+ sid,+ "server_restart",+ {+ "emittedAt": _utcnow()+ .isoformat(timespec="milliseconds")+ .replace("+00:00", "Z"),+ "runtimeId": runtime.get_runtime_id(),+ },+ handler_id=self._identifier,+ )+ if _ws_debug_enabled():+ PrintStyle.info(+ f"server_restart broadcast emitted to namespace={namespace} sid={sid}"+ )+ lifecycle_payload = {+ "namespace": namespace,+ "sid": sid,+ "connectionCount": connection_count,+ "timestamp": self._timestamp(),+ }+ await self._publish_diagnostic_event(+ {+ "kind": "lifecycle",+ "event": "connect",+ **lifecycle_payload,+ }+ )+ self._schedule_lifecycle_broadcast(+ namespace, LIFECYCLE_CONNECT_EVENT, lifecycle_payload+ )++ async def handle_disconnect(self, namespace: str, sid: str) -> None:+ self._ensure_dispatcher_loop()+ identity: ConnectionIdentity = (namespace, sid)+ with self.lock:+ self.connections.pop(identity, None)+ # Keep identity in _known_sids so emit_to buffers instead of raising+ # session tracking cleanup+ user_bucket = self.sid_to_user.pop(identity, None)+ if self._ALL_USERS_BUCKET in self.user_to_sids:+ self.user_to_sids[self._ALL_USERS_BUCKET].discard(identity)+ if not self.user_to_sids[self._ALL_USERS_BUCKET]:+ self.user_to_sids.pop(self._ALL_USERS_BUCKET, None)+ if user_bucket and user_bucket in self.user_to_sids:+ self.user_to_sids[user_bucket].discard(identity)+ if not self.user_to_sids[user_bucket]:+ self.user_to_sids.pop(user_bucket, None)+ connection_count = sum(+ 1 for conn_identity in self.connections if conn_identity[0] == namespace+ )+ self.unregister_diagnostic_watcher(namespace, sid)+ PrintStyle.info(f"WebSocket disconnected: namespace={namespace} sid={sid}")+ await self._run_lifecycle(namespace, lambda h: h.on_disconnect(sid))+ lifecycle_payload = {+ "namespace": namespace,+ "sid": sid,+ "connectionCount": connection_count,+ "timestamp": self._timestamp(),+ }+ await self._publish_diagnostic_event(+ {+ "kind": "lifecycle",+ "event": "disconnect",+ **lifecycle_payload,+ }+ )+ self._schedule_lifecycle_broadcast(+ namespace, LIFECYCLE_DISCONNECT_EVENT, lifecycle_payload+ )++ async def route_event(+ self,+ namespace: str,+ event_type: str,+ data: dict[str, Any],+ sid: str,+ ack: Optional[Callable[[Any], None]] = None,+ *,+ include_handlers: Set[str] | None = None,+ exclude_handlers: Set[str] | None = None,+ allow_exclude: bool = False,+ handler_id: str | None = None,+ ) -> dict[str, Any]:+ self._ensure_dispatcher_loop()+ incoming = dict(data or {})+ correlation_id = self._resolve_correlation_id(incoming)+ self._debug(+ f"Routing event namespace={namespace} '{event_type}' sid={sid} correlation={correlation_id}"+ )++ include_meta_raw = incoming.pop("includeHandlers", None)+ exclude_meta_raw = incoming.pop("excludeHandlers", None)++ if "data" in incoming and isinstance(incoming.get("data"), dict):+ handler_payload = dict(incoming.get("data") or {})+ if "excludeSids" in incoming:+ handler_payload["excludeSids"] = incoming.get("excludeSids")+ else:+ handler_payload = dict(incoming)++ handler_payload["correlationId"] = correlation_id++ try:+ include_meta = self._normalize_handler_filter(+ include_meta_raw, "includeHandlers"+ )+ except ValueError as exc:+ error = self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="INVALID_FILTER",+ message=str(exc),+ correlation_id=correlation_id,+ )+ if ack:+ ack({"correlationId": correlation_id, "results": [error]})+ return {"correlationId": correlation_id, "results": [error]}++ try:+ exclude_meta = self._normalize_handler_filter(+ exclude_meta_raw, "excludeHandlers"+ )+ except ValueError as exc:+ error = self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="INVALID_FILTER",+ message=str(exc),+ correlation_id=correlation_id,+ )+ payload_error = {"correlationId": correlation_id, "results": [error]}+ if ack:+ ack(payload_error)+ return payload_error++ if exclude_meta_raw is not None and not allow_exclude:+ error = self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="INVALID_FILTER",+ message="excludeHandlers is not supported for this operation",+ correlation_id=correlation_id,+ )+ if ack:+ ack({"correlationId": correlation_id, "results": [error]})+ return {"correlationId": correlation_id, "results": [error]}++ if include_handlers is not None and include_meta is not None:+ if include_handlers != include_meta:+ error = self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="INVALID_FILTER",+ message="Conflicting includeHandlers filters supplied",+ correlation_id=correlation_id,+ )+ if ack:+ ack({"correlationId": correlation_id, "results": [error]})+ return {"correlationId": correlation_id, "results": [error]}++ if allow_exclude and exclude_handlers is not None and exclude_meta is not None:+ if exclude_handlers != exclude_meta:+ error = self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="INVALID_FILTER",+ message="Conflicting excludeHandlers filters supplied",+ correlation_id=correlation_id,+ )+ if ack:+ ack({"correlationId": correlation_id, "results": [error]})+ return {"correlationId": correlation_id, "results": [error]}++ include = include_handlers or include_meta+ exclude = exclude_handlers or (exclude_meta if allow_exclude else None)++ try:+ validate_event_type(event_type)+ except (TypeError, ValueError) as exc:+ error = self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="INVALID_EVENT",+ message=str(exc),+ correlation_id=correlation_id,+ )+ if ack:+ ack({"correlationId": correlation_id, "results": [error]})+ return {"correlationId": correlation_id, "results": [error]}++ registered = self.handlers.get(namespace, [])+ if not registered:+ PrintStyle.warning(f"No handlers registered for namespace '{namespace}'")+ error = self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="NO_HANDLERS",+ message=f"No handler for namespace '{namespace}'",+ correlation_id=correlation_id,+ )+ if ack:+ ack({"correlationId": correlation_id, "results": [error]})+ return {"correlationId": correlation_id, "results": [error]}++ try:+ selected_handlers, _ = self._select_handlers(+ namespace, include=include, exclude=exclude+ )+ except ValueError as exc:+ error = self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="INVALID_FILTER",+ message=str(exc),+ correlation_id=correlation_id,+ )+ if ack:+ ack({"correlationId": correlation_id, "results": [error]})+ return {"correlationId": correlation_id, "results": [error]}++ if not selected_handlers:+ error = self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="NO_HANDLERS",+ message=f"No handler for '{event_type}' after applying filters",+ correlation_id=correlation_id,+ )+ if ack:+ ack({"correlationId": correlation_id, "results": [error]})+ return {"correlationId": correlation_id, "results": [error]}++ with self.lock:+ info = self.connections.get((namespace, sid))+ if info:+ info.last_activity = _utcnow()++ executions = await asyncio.gather(+ *[+ self._invoke_handler(handler, event_type, dict(handler_payload), sid)+ for handler in selected_handlers+ ]+ )++ results: List[dict[str, Any]] = []+ for execution in executions:+ handler = execution.handler+ value = execution.value+ duration_ms = execution.duration_ms++ if isinstance(value, Exception): # pragma: no cover - defensive logging+ PrintStyle.error(+ f"Error in handler {handler.identifier} for '{event_type}' (correlation {correlation_id}): {value}"+ )+ results.append(+ self._build_error_result(+ handler_id=handler.identifier,+ code="HANDLER_ERROR",+ message="Internal server error",+ details=str(value),+ correlation_id=correlation_id,+ duration_ms=duration_ms,+ )+ )+ continue++ if isinstance(value, WsResult):+ results.append(+ value.as_result(+ handler_id=handler.identifier,+ fallback_correlation_id=correlation_id,+ duration_ms=duration_ms,+ )+ )+ continue++ if value is None:+ helper_result = WsResult(ok=True)+ elif isinstance(value, dict):+ helper_result = WsResult(ok=True, data=value)+ else:+ helper_result = WsResult(ok=True, data={"result": value})++ results.append(+ helper_result.as_result(+ handler_id=handler.identifier,+ fallback_correlation_id=correlation_id,+ duration_ms=duration_ms,+ )+ )++ await self._publish_diagnostic_event(+ lambda: {+ "kind": "inbound",+ "sourceNamespace": namespace,+ "namespace": namespace,+ "eventType": event_type,+ "sid": sid,+ "correlationId": correlation_id,+ "timestamp": self._timestamp(),+ "handlerCount": len(selected_handlers),+ "durationMs": sum((exec.duration_ms or 0.0) for exec in executions),+ "resultSummary": self._summarize_results(results),+ "payloadSummary": self._summarize_payload(handler_payload),+ }+ )++ response_payload = {"correlationId": correlation_id, "results": results}+ if ack:+ ack(response_payload)+ self._debug(+ f"Completed event namespace={namespace} '{event_type}' sid={sid} correlation={correlation_id}"+ )+ return response_payload++ async def request_for_sid(+ self,+ *,+ namespace: str,+ sid: str,+ event_type: str,+ data: dict[str, Any],+ timeout_ms: int = 0,+ handler_id: str | None = None,+ include_handlers: Set[str] | None = None,+ ) -> dict[str, Any]:+ payload = dict(data or {})+ correlation_id = self._resolve_correlation_id(payload)++ with self.lock:+ connected = (namespace, sid) in self.connections+ if not connected:+ return {+ "correlationId": correlation_id,+ "results": [+ self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="CONNECTION_NOT_FOUND",+ message=f"Connection '{sid}' not found in namespace '{namespace}'",+ correlation_id=correlation_id,+ )+ ],+ }++ async def _invoke() -> dict[str, Any]:+ return await self.route_event(+ namespace,+ event_type,+ payload,+ sid,+ include_handlers=include_handlers,+ handler_id=handler_id,+ )++ if timeout_ms and timeout_ms > 0:+ try:+ return await asyncio.wait_for(_invoke(), timeout=timeout_ms / 1000)+ except asyncio.TimeoutError:+ PrintStyle.warning(+ f"request timeout for sid {sid} event '{event_type}'"+ )+ return {+ "correlationId": correlation_id,+ "results": [+ self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="TIMEOUT",+ message="Request timeout",+ correlation_id=correlation_id,+ )+ ],+ }+ return await _invoke()++ async def route_event_all(+ self,+ namespace: str,+ event_type: str,+ data: dict[str, Any],+ *,+ timeout_ms: int = 0,+ exclude_handlers: Set[str] | None = None,+ handler_id: str | None = None,+ ) -> list[dict[str, Any]]:+ """Fan-out a request to all active connections and aggregate responses."""++ base_payload = dict(data or {})+ exclude_meta_raw = base_payload.pop("excludeHandlers", None)+ exclude_combined: Set[str] | None = exclude_handlers+ correlation_id = self._resolve_correlation_id(base_payload)++ if exclude_meta_raw is not None:+ try:+ exclude_meta = self._normalize_handler_filter(+ exclude_meta_raw, "excludeHandlers"+ )+ except ValueError as exc:+ error = self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="INVALID_FILTER",+ message=str(exc),+ correlation_id=correlation_id,+ )+ return [+ {+ "sid": "__invalid__",+ "correlationId": correlation_id,+ "results": [error],+ }+ ]++ if exclude_combined is None:+ exclude_combined = exclude_meta+ elif exclude_meta is not None and exclude_combined != exclude_meta:+ error = self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="INVALID_FILTER",+ message="Conflicting excludeHandlers filters supplied",+ correlation_id=correlation_id,+ )+ return [+ {+ "sid": "__invalid__",+ "correlationId": correlation_id,+ "results": [error],+ }+ ]++ self._debug(+ f"Starting requestAll namespace={namespace} for '{event_type}' correlation={correlation_id}"+ )++ with self.lock:+ active_sids = [+ conn_identity[1]+ for conn_identity in self.connections.keys()+ if conn_identity[0] == namespace+ ]+ if not active_sids:+ self._debug(+ f"No active connections for requestAll namespace={namespace} '{event_type}' correlation={correlation_id}"+ )+ return []++ timeout_seconds = timeout_ms / 1000 if timeout_ms and timeout_ms > 0 else None++ async def _invoke_for_sid(target_sid: str) -> dict[str, Any]:+ async def _dispatch() -> dict[str, Any]:+ return await self.route_event(+ namespace,+ event_type,+ base_payload,+ target_sid,+ allow_exclude=True,+ exclude_handlers=exclude_combined,+ handler_id=handler_id,+ )++ if timeout_seconds is None:+ return await _dispatch()++ try:+ task = asyncio.create_task(_dispatch())+ return await asyncio.wait_for(+ asyncio.shield(task), timeout=timeout_seconds+ )+ except asyncio.TimeoutError:+ PrintStyle.warning(+ f"requestAll timeout for sid {target_sid} correlation={correlation_id}"+ )+ # Ensure any late exceptions are observed so asyncio does not log+ # "Task exception was never retrieved".+ try:+ task.add_done_callback(lambda t: t.exception()) # type: ignore[arg-type]+ except Exception: # pragma: no cover - defensive+ pass+ return {+ "correlationId": correlation_id,+ "results": [+ self._build_error_result(+ handler_id=handler_id or self._identifier,+ code="TIMEOUT",+ message="Request timeout",+ correlation_id=correlation_id,+ )+ ],+ }++ tasks = {sid: asyncio.create_task(_invoke_for_sid(sid)) for sid in active_sids}++ aggregated: list[dict[str, Any]] = []+ for sid, task in tasks.items():+ result = await task+ if isinstance(result, dict):+ aggregated.append(+ {+ "sid": sid,+ "correlationId": result.get("correlationId", correlation_id),+ "results": result.get("results", []),+ }+ )+ else:+ aggregated.append(+ {+ "sid": sid,+ "correlationId": correlation_id,+ "results": result,+ }+ )++ self._debug(+ f"Completed requestAll namespace={namespace} for '{event_type}' correlation={correlation_id}"+ )+ return aggregated++ def _wrap_envelope(+ self,+ handler_id: str | None,+ data: dict[str, Any],+ *,+ correlation_id: str | None = None,+ ) -> dict[str, Any]:+ hid = handler_id or self._identifier+ ts = _utcnow().isoformat(timespec="milliseconds").replace("+00:00", "Z")+ event_id = str(uuid.uuid4())+ correlation = correlation_id or str(uuid.uuid4())+ return {+ "handlerId": hid,+ "eventId": event_id,+ "correlationId": correlation,+ "ts": ts,+ "data": data or {},+ }++ async def emit_to(+ self,+ namespace: str,+ sid: str,+ event_type: str,+ data: dict[str, Any],+ *,+ handler_id: str | None = None,+ correlation_id: str | None = None,+ diagnostic: bool = False,+ ) -> None:+ envelope = self._wrap_envelope(+ handler_id,+ data,+ correlation_id=correlation_id,+ )+ delivered = False+ buffered = False+ identity: ConnectionIdentity = (namespace, sid)++ with self.lock:+ connected = identity in self.connections+ known = identity in self._known_sids or identity in self.buffers++ if connected:+ self._debug(+ "Emit to namespace=%s sid=%s event=%s eventId=%s correlationId=%s handlerId=%s"+ % (+ namespace,+ sid,+ event_type,+ envelope.get("eventId"),+ envelope.get("correlationId"),+ envelope.get("handlerId"),+ )+ )+ await self._run_on_dispatcher_loop(+ self.socketio.emit(event_type, envelope, to=sid, namespace=namespace)+ )+ delivered = True+ else:+ if not known:+ raise ConnectionNotFoundError(sid, namespace=namespace)+ with self.lock:+ self._buffer_event(+ identity,+ event_type,+ data,+ handler_id,+ envelope["correlationId"],+ )+ buffered = True++ if not diagnostic:+ await self._publish_diagnostic_event(+ lambda: {+ "kind": "outbound",+ "direction": "emit_to",+ "eventType": event_type,+ "namespace": namespace,+ "sid": sid,+ "correlationId": envelope["correlationId"],+ "handlerId": envelope["handlerId"],+ "timestamp": self._timestamp(),+ "delivered": delivered,+ "buffered": buffered,+ "payloadSummary": self._summarize_payload(data),+ }+ )++ async def send_data(+ self,+ endpoint_name: str,+ event_type: str,+ data: dict[str, Any],+ connection_id: str | None = None,+ ) -> None:+ if connection_id is not None:+ await self.emit_to(endpoint_name, connection_id, event_type, data)+ return+ await self.broadcast(endpoint_name, event_type, data)++ async def broadcast(+ self,+ namespace: str,+ event_type: str,+ data: dict[str, Any],+ *,+ exclude_sids: str | Iterable[str] | None = None,+ handler_id: str | None = None,+ correlation_id: str | None = None,+ diagnostic: bool = False,+ ) -> None:+ excluded = self._normalize_sid_filter(exclude_sids)++ targets: list[str] = []+ with self.lock:+ current_identities = list(self.connections.keys())+ for conn_identity in current_identities:+ if conn_identity[0] != namespace:+ continue+ sid = conn_identity[1]+ if sid in excluded:+ continue+ targets.append(sid)++ if targets:+ envelope = self._wrap_envelope(+ handler_id,+ data,+ correlation_id=correlation_id,+ )+ coros = [+ self._run_on_dispatcher_loop(+ self.socketio.emit(event_type, envelope, to=sid, namespace=namespace)+ )+ for sid in targets+ ]+ await asyncio.gather(*coros)++ if not diagnostic:+ await self._publish_diagnostic_event(+ lambda: {+ "kind": "outbound",+ "direction": "broadcast",+ "eventType": event_type,+ "namespace": namespace,+ "targets": targets[:10],+ "targetCount": len(targets),+ "correlationId": correlation_id,+ "handlerId": handler_id or self._identifier,+ "timestamp": self._timestamp(),+ "payloadSummary": self._summarize_payload(data),+ }+ )++ async def _run_lifecycle(+ self, namespace: str, fn: Callable[[WsHandler], Any]+ ) -> None:+ seen: Set[WsHandler] = set()+ coros: list[Any] = []+ for handler in self.handlers.get(namespace, []):+ if handler in seen:+ continue+ seen.add(handler)+ coros.append(self._get_handler_worker().execute_inside(fn, handler))+ if coros:+ await asyncio.gather(*coros, return_exceptions=True)++ def _buffer_event(+ self,+ identity: ConnectionIdentity,+ event_type: str,+ data: dict[str, Any],+ handler_id: str | None,+ correlation_id: str | None,+ ) -> None:+ namespace, sid = identity+ buffer = self.buffers[identity]+ buffer.append(+ BufferedEvent(+ event_type=event_type,+ data=data,+ handler_id=handler_id,+ correlation_id=correlation_id,+ )+ )+ while len(buffer) > BUFFER_MAX_SIZE:+ dropped = buffer.popleft()+ PrintStyle.warning(+ f"Dropping buffered event '{dropped.event_type}' for namespace={namespace} sid={sid} (overflow)"+ )+ self._debug(+ f"Buffered event namespace={namespace} '{event_type}' sid={sid} (queue length={len(buffer)})"+ )++ async def _flush_buffer(self, identity: ConnectionIdentity) -> None:+ self._ensure_dispatcher_loop()+ buffer = self.buffers.get(identity)+ if not buffer:+ return+ namespace, sid = identity+ now = _utcnow()+ delivered = 0+ while buffer:+ event = buffer.popleft()+ if now - event.timestamp > BUFFER_TTL:+ self._debug(+ f"Discarding expired buffered event '{event.event_type}' for sid {sid}"+ )+ continue+ envelope = self._wrap_envelope(+ event.handler_id,+ event.data,+ correlation_id=event.correlation_id,+ )+ self._debug(+ "Flush to sid=%s event=%s eventId=%s correlationId=%s handlerId=%s"+ % (+ sid,+ event.event_type,+ envelope.get("eventId"),+ envelope.get("correlationId"),+ envelope.get("handlerId"),+ )+ )+ await self._run_on_dispatcher_loop(+ self.socketio.emit(+ event.event_type, envelope, to=sid, namespace=namespace+ )+ )+ delivered += 1+ if identity in self.buffers:+ self.buffers.pop(identity, None)+ if delivered:+ PrintStyle.info(+ f"Flushed {delivered} buffered event(s) to namespace={namespace} sid={sid}"+ )++ def _build_error_result(+ self,+ *,+ handler_id: str | None = None,+ code: str,+ message: str,+ details: str | None = None,+ correlation_id: str | None = None,+ duration_ms: float | None = None,+ ) -> dict[str, Any]:+ error_payload = {"code": code, "error": message}+ if details:+ error_payload["details"] = details+ result: dict[str, Any] = {+ "handlerId": handler_id or self._identifier,+ "ok": False,+ "error": error_payload,+ }+ if correlation_id is not None:+ result["correlationId"] = correlation_id+ if duration_ms is not None:+ result["durationMs"] = round(duration_ms, 4)+ return result++ # Session tracking helpers (single-user defaults)+ def get_sids_for_user(self, user: str | None = None) -> list[ConnectionIdentity]:+ """Return connection identities for a user; single-user default returns all."""+ with self.lock:+ bucket = self._ALL_USERS_BUCKET if user is None else user+ return list(self.user_to_sids.get(bucket, set()))++ def get_user_for_sid(self, namespace: str, sid: str) -> str | None:+ """Return user identifier for a connection or None."""+ identity: ConnectionIdentity = (namespace, sid)+ with self.lock:+ return self.sid_to_user.get(identity)++ def set_server_restart_broadcast(self, enabled: bool) -> None:+ """Enable or disable automatic server restart broadcasts."""++ self._server_restart_enabled = bool(enabled)diff --git a/run_ui.py b/run_ui.pyindex 41fc9afc9..fe1e2dbd5 100644--- a/run_ui.py+++ b/run_ui.py@@ -14,9 +14,8 @@ import initializefrom helpers import files, git, mcp_server, fasta2a_server, settings as settings_helper, extensionfrom helpers.files import get_abs_pathfrom helpers import runtime, dotenv, process-from helpers.websocket import WebSocketHandler, validate_ws_originfrom helpers.api import register_api_route, requires_auth, csrf_protect-from helpers.ws import register_ws_namespace+from helpers.ws import register_ws_namespace, validate_ws_originfrom helpers.print_style import PrintStylefrom helpers import loginimport socketio # type: ignore[import-untyped]@@ -24,8 +23,7 @@ from socketio import ASGIApp, packetfrom starlette.applications import Starlettefrom starlette.routing import Mountfrom uvicorn.middleware.wsgi import WSGIMiddleware-from helpers.websocket_manager import WebSocketManager, set_shared_websocket_manager-from helpers.websocket_namespace_discovery import discover_websocket_namespaces+from helpers.ws_manager import WsManager, set_shared_ws_managerfrom flask import send_file# disable logging@@ -73,11 +71,11 @@ socketio_server = socketio.AsyncServer(max_http_buffer_size=50 * 1024 * 1024,)-websocket_manager = WebSocketManager(socketio_server, lock)-set_shared_websocket_manager(websocket_manager)+ws_manager = WsManager(socketio_server, lock)+set_shared_ws_manager(ws_manager)_settings = settings_helper.get_settings()settings_helper.set_runtime_settings_snapshot(_settings)-websocket_manager.set_server_restart_broadcast(+ws_manager.set_server_restart_broadcast(_settings.get("websocket_server_restart_enabled", True))@@ -191,160 +189,6 @@ async def _serve_plugin_asset(plugin_name, asset_path):return Response("Error serving asset", 500)-def _build_websocket_handlers_by_namespace(- socketio_server: socketio.AsyncServer,- lock: threading.RLock,-) -> dict[str, list[WebSocketHandler]]:- discoveries = discover_websocket_namespaces(- handlers_folder="python/websocket_handlers",- include_root_default=True,- )-- handlers_by_namespace: dict[str, list[WebSocketHandler]] = {}- for discovery in discoveries:- namespace = discovery.namespace- for handler_cls in discovery.handler_classes:- handler = handler_cls.get_instance(socketio_server, lock)- handlers_by_namespace.setdefault(namespace, []).append(handler)-- return handlers_by_namespace---def configure_websocket_namespaces(- *,- webapp: Flask,- socketio_server: socketio.AsyncServer,- websocket_manager: WebSocketManager,- handlers_by_namespace: dict[str, list[WebSocketHandler]],-) -> set[str]:- namespace_map: dict[str, list[WebSocketHandler]] = {- namespace: list(handlers) for namespace, handlers in handlers_by_namespace.items()- }-- # Always include the reserved root namespace. It is unhandled for application events by- # default, but request-style calls must resolve deterministically with NO_HANDLERS.- namespace_map.setdefault("/", [])-- websocket_manager.register_handlers(namespace_map)-- allowed_namespaces = set(namespace_map.keys())- original_handle_connect = socketio_server._handle_connect # type: ignore[attr-defined]-- async def _handle_connect_with_namespace_gatekeeper(eio_sid, namespace, data):- requested = namespace or "/"- if requested not in allowed_namespaces:- await socketio_server._send_packet(- eio_sid,- socketio_server.packet_class(- packet.CONNECT_ERROR,- data={- "message": "UNKNOWN_NAMESPACE",- "data": {"code": "UNKNOWN_NAMESPACE", "namespace": requested},- },- namespace=requested,- ),- )- return- await original_handle_connect(eio_sid, namespace, data)-- socketio_server._handle_connect = _handle_connect_with_namespace_gatekeeper # type: ignore[assignment]-- def _register_namespace_handlers(- namespace: str, namespace_handlers: list[WebSocketHandler]- ) -> None:- # A namespace is the WebSocket equivalent of an API endpoint.- # Security requirements must be consistent within the namespace (no any()-based union).- auth_required = False- csrf_required = False- if namespace_handlers:- auth_required = bool(namespace_handlers[0].requires_auth())- csrf_required = bool(namespace_handlers[0].requires_csrf())- for handler in namespace_handlers[1:]:- if (- bool(handler.requires_auth()) != auth_required- or bool(handler.requires_csrf()) != csrf_required- ):- raise ValueError(- f"WebSocket namespace {namespace!r} has mixed auth/csrf requirements across handlers"- )-- @socketio_server.on("connect", namespace=namespace)- async def _connect( # type: ignore[override]- sid,- environ,- _auth,- _namespace: str = namespace,- _auth_required: bool = auth_required,- _csrf_required: bool = csrf_required,- ):- with webapp.request_context(environ):- origin_ok, origin_reason = validate_ws_origin(environ)- if not origin_ok:- PrintStyle.warning(- f"WebSocket origin validation failed for {_namespace} {sid}: {origin_reason or 'invalid'}"- )- return False-- if _auth_required:- credentials_hash = login.get_credentials_hash()- if credentials_hash:- if session.get("authentication") != credentials_hash:- PrintStyle.warning(- f"WebSocket authentication failed for {_namespace} {sid}: session not valid"- )- return False- else:- PrintStyle.debug(- "WebSocket authentication required but credentials not configured; proceeding"- )-- if _csrf_required:- expected_token = session.get("csrf_token")- if not isinstance(expected_token, str) or not expected_token:- PrintStyle.warning(- f"WebSocket CSRF validation failed for {_namespace} {sid}: csrf_token not initialized"- )- return False-- auth_token = None- if isinstance(_auth, dict):- auth_token = _auth.get("csrf_token") or _auth.get("csrfToken")- if not isinstance(auth_token, str) or not auth_token:- PrintStyle.warning(- f"WebSocket CSRF validation failed for {_namespace} {sid}: missing csrf_token in auth"- )- return False- if auth_token != expected_token:- PrintStyle.warning(- f"WebSocket CSRF validation failed for {_namespace} {sid}: csrf_token mismatch"- )- return False-- cookie_name = f"csrf_token_{runtime.get_runtime_id()}"- cookie_token = request.cookies.get(cookie_name)- if cookie_token != expected_token:- PrintStyle.warning(- f"WebSocket CSRF validation failed for {_namespace} {sid}: csrf cookie mismatch"- )- return False-- user_id = session.get("user_id") or "single_user"- await websocket_manager.handle_connect(_namespace, sid, user_id=user_id)- return True-- @socketio_server.on("disconnect", namespace=namespace)- async def _disconnect(sid, _namespace: str = namespace): # type: ignore[override]- await websocket_manager.handle_disconnect(_namespace, sid)-- @socketio_server.on("*", namespace=namespace)- async def _catch_all(event, sid, data, _namespace: str = namespace):- payload = data or {}- return await websocket_manager.route_event(_namespace, event, payload, sid)-- for namespace, namespace_handlers in namespace_map.items():- _register_namespace_handlers(namespace, namespace_handlers)-- return allowed_namespacesdef run():@@ -373,16 +217,7 @@ def run():register_api_route(webapp, lock)- handlers_by_namespace = _build_websocket_handlers_by_namespace(socketio_server, lock)- allowed_namespaces = configure_websocket_namespaces(- webapp=webapp,- socketio_server=socketio_server,- websocket_manager=websocket_manager,- handlers_by_namespace=handlers_by_namespace,- )-- register_ws_namespace(socketio_server, webapp, lock)- allowed_namespaces.add("/ws")+ register_ws_namespace(socketio_server, webapp, lock, manager=ws_manager)init_a0()@@ -443,7 +278,7 @@ def run():def wait_for_health(host: str, port: int):- url = f"http://{host}:{port}/health"+ url = f"http://{host}:{port}/api/health"while True:try:with urllib.request.urlopen(url, timeout=2) as resp: