From 8c8ea819a8e8cd895a4d6c7b830496a38fc016e7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 8 Aug 2025 14:08:33 +0000 Subject: [PATCH] Improve WebSocket hook: limit queue size and add cleanup on unmount Co-authored-by: nate --- apps/web/src/hooks/useWebSocket/useWebSocket.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/apps/web/src/hooks/useWebSocket/useWebSocket.ts b/apps/web/src/hooks/useWebSocket/useWebSocket.ts index d554c2479..0bdbc4be7 100644 --- a/apps/web/src/hooks/useWebSocket/useWebSocket.ts +++ b/apps/web/src/hooks/useWebSocket/useWebSocket.ts @@ -22,6 +22,7 @@ interface QueuedMessage { } const BASE_DELAY = 3000; +const MAX_QUEUE_LENGTH = 5000; const useWebSocket = ({ url, checkTokenValidity, canConnect, onMessage }: WebSocketHookProps) => { const { online } = useNetwork(); @@ -117,6 +118,11 @@ const useWebSocket = ({ url, checkTokenValidity, canConnect, onMessage }: WebSoc messageQueue.current.push(queuedMessage); + // Bound the queue length to prevent unbounded memory growth + if (messageQueue.current.length > MAX_QUEUE_LENGTH) { + messageQueue.current.splice(0, messageQueue.current.length - MAX_QUEUE_LENGTH); + } + if (!processing.current) { processQueue(); } @@ -224,6 +230,15 @@ const useWebSocket = ({ url, checkTokenValidity, canConnect, onMessage }: WebSoc handleVisibilityChange(); }); + // Cleanup on unmount: close socket and clear queues + useEffect(() => { + return () => { + disconnect(); + messageQueue.current = []; + sendQueue.current = []; + }; + }, [disconnect]); + return { sendJSONMessage, disconnect,