manager.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import time
  2. from dataclasses import dataclass
  3. from fastapi import WebSocket
  4. from openhands.core.config import AppConfig
  5. from openhands.core.logger import openhands_logger as logger
  6. from openhands.events.stream import session_exists
  7. from openhands.runtime.base import RuntimeUnavailableError
  8. from openhands.server.session.conversation import Conversation
  9. from openhands.server.session.session import Session
  10. from openhands.storage.files import FileStore
  11. @dataclass
  12. class SessionManager:
  13. config: AppConfig
  14. file_store: FileStore
  15. def add_or_restart_session(self, sid: str, ws_conn: WebSocket) -> Session:
  16. return Session(
  17. sid=sid, file_store=self.file_store, ws=ws_conn, config=self.config
  18. )
  19. async def attach_to_conversation(self, sid: str) -> Conversation | None:
  20. start_time = time.time()
  21. if not await session_exists(sid, self.file_store):
  22. return None
  23. c = Conversation(sid, file_store=self.file_store, config=self.config)
  24. try:
  25. await c.connect()
  26. except RuntimeUnavailableError as e:
  27. logger.error(f'Error connecting to conversation {c.sid}: {e}')
  28. return None
  29. end_time = time.time()
  30. logger.info(
  31. f'Conversation {c.sid} connected in {end_time - start_time} seconds'
  32. )
  33. return c
  34. async def detach_from_conversation(self, conversation: Conversation):
  35. await conversation.disconnect()