from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from app.api.dependencies import ServiceContainer
import json
def create_workspace_router(services: ServiceContainer) -> APIRouter:
router = APIRouter()
@router.websocket("/ws/workspace/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: str):
await websocket.accept()
print(f"WebSocket connection accepted for client: {client_id}")
# Send a welcome message to confirm the connection is active
await websocket.send_text(json.dumps({
"type": "connection_established",
"message": f"Connected to AI Hub. Client ID: {client_id}"
}))
try:
await websocket.send_text(json.dumps({
"type": "connection_established",
"message": f"Connected to AI Hub. Client ID: {client_id}"
}))
while True:
message = await websocket.receive_text()
data = json.loads(message)
# The endpoint's only job is to dispatch the message to the service
await services.workspace_service.dispatch_message(websocket, data)
except WebSocketDisconnect:
print(f"WebSocket connection disconnected for client: {client_id}")
except Exception as e:
print(f"An error occurred: {e}")
finally:
print(f"Closing WebSocket for client: {client_id}")
return router