Server side implementation for interactive entry edits

This commit is contained in:
2024-11-23 15:34:33 +01:00
parent bb74fd3621
commit dbc0068a82
28 changed files with 749 additions and 553 deletions

View File

@@ -0,0 +1,59 @@
from aiohttp import web, WSMsgType
from typing import Dict, Set
from ..entry import Entry
from ..web_agent import WebAgent
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