From 84d5b533f7550fb920171767aded192c5fc2a5b0 Mon Sep 17 00:00:00 2001 From: Vadym Samoilenko Date: Mon, 2 Mar 2026 12:30:51 +0000 Subject: [PATCH] Handle WebSocket disconnect gracefully during analysis When a client disconnects (navigates away, closes tab) while analysis is still running, the result send raises RuntimeError "WebSocket is not connected". Catch this specifically as INFO rather than ERROR, and guard the fallback send_message in the general Exception handler so it doesn't raise a second uncaught error. Co-Authored-By: Claude Sonnet 4.6 --- backend/app/main.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/backend/app/main.py b/backend/app/main.py index 487343c..eae0f69 100755 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -238,10 +238,20 @@ async def websocket_analyze(websocket: WebSocket): except WebSocketDisconnect: logger.info(f"[MAIN] Client {client_id} disconnected") manager.disconnect(client_id) + except RuntimeError as e: + # Client disconnected mid-analysis (e.g. navigated away before result arrived) + if "not connected" in str(e).lower() or "websocket" in str(e).lower(): + logger.info(f"[MAIN] Client {client_id} disconnected before result was sent") + else: + logger.error(f"[MAIN] RuntimeError for client {client_id}: {str(e)}") + manager.disconnect(client_id) except Exception as e: logger.error(f"[MAIN] Error for client {client_id}: {str(e)}") - await manager.send_message(client_id, { - "type": "error", - "message": str(e) - }) + try: + await manager.send_message(client_id, { + "type": "error", + "message": str(e) + }) + except Exception: + pass manager.disconnect(client_id)