from aiohttp import web, WSMsgType from typing import Dict, Set from .util import wrap_async from ..web_agent import WebAgent, AgentState class StateWebSocket: """ WebSocket handler for agent state changes. Broadcasts state updates to all connected clients. """ def __init__(self, agent: WebAgent): self._agent = agent self._clients: Set[web.WebSocketResponse] = set() self._agent.add_state_change_handler(wrap_async(self._handle_change)) self._agent.add_selected_llm_change_handler(wrap_async(self._handle_change)) async def _broadcast_message(self, message: Dict): """Broadcast message to all connected clients.""" disconnected = set() for ws in self._clients: try: await ws.send_json(message) except ConnectionResetError: disconnected.add(ws) self._clients -= disconnected async def _handle_change(self, arg): """Handle changes to the active LLM.""" await self._broadcast_message({ "state": self._agent.state.name, "active_llm": self._agent.active_llm }) async def handle_connection(self, request: web.Request) -> web.WebSocketResponse: """Handle new WebSocket connections.""" ws = web.WebSocketResponse(heartbeat=30) await ws.prepare(request) try: # Send initial state await ws.send_json({ "state": self._agent.state.name, "active_llm": self._agent.active_llm }) self._clients.add(ws) async for msg in ws: if msg.type == WSMsgType.ERROR: print(f"WebSocket connection closed with error: {ws.exception()}") finally: self._clients.remove(ws) return ws