from aiohttp import web, WSMsgType from typing import Dict, Set import asyncio from .util import wrap_async from ..web_io_buffer import WebIOBuffer class StdoutWebSocket: """ WebSocket handler for stdout changes. Broadcasts stdout updates to all connected clients. """ def __init__(self, io_buffer: WebIOBuffer): self._io_buffer = io_buffer self._clients: Set[web.WebSocketResponse] = set() self._io_buffer.add_stdout_change_handler(wrap_async(self._handle_stdout_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_stdout_change(self, output: str): """Handle stdout changes from the WebIOBuffer.""" await self._broadcast_message({ "output": output }) async def handle_connection(self, request: web.Request) -> web.WebSocketResponse: """Handle new WebSocket connections.""" ws = web.WebSocketResponse(heartbeat=30) await ws.prepare(request) self._clients.add(ws) try: # Send initial stdout content await ws.send_json({ "output": self._io_buffer.get_stdout() }) 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