from aiohttp import web, WSMsgType from typing import Dict, Set from ..working_memory import WorkingMemory from .util import wrap_async class MemoryWebSocket: """ WebSocket handler for working memory changes. Broadcasts memory updates to all connected clients. """ def __init__(self, working_memory: WorkingMemory): self._working_memory = working_memory self._clients: Set[web.WebSocketResponse] = set() self._working_memory.add_change_handler(wrap_async(self._handle_memory_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_memory_change(self): """Handle working memory changes.""" entries = self._working_memory.get_entries() await self._broadcast_message({ "type": "memory_state", "entries": [e.serialize() for e in entries] }) 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 memory state entries = self._working_memory.get_entries() await ws.send_json({ "type": "memory_state", "entries": [e.serialize() for e in entries] }) 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