From ffe9a2435b4aa4fcd8f20e973a8b65363c1068b2 Mon Sep 17 00:00:00 2001 From: Peter Steinberger Date: Fri, 26 Dec 2025 09:27:01 +0000 Subject: [PATCH] fix: clean up web inbox listeners on close --- src/web/inbound.ts | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/web/inbound.ts b/src/web/inbound.ts index 8b11d3b68..7dbe9bfe8 100644 --- a/src/web/inbound.ts +++ b/src/web/inbound.ts @@ -115,9 +115,12 @@ export async function monitorWebInbox(options: { } }; - sock.ev.on("messages.upsert", async (upsert) => { + const handleMessagesUpsert = async (upsert: { + type?: string; + messages?: Array; + }) => { if (upsert.type !== "notify") return; - for (const msg of upsert.messages) { + for (const msg of upsert.messages ?? []) { const id = msg.key?.id ?? undefined; // De-dupe on message id; Baileys can emit retries. if (id && seen.has(id)) continue; @@ -295,11 +298,12 @@ export async function monitorWebInbox(options: { ); } } - }); + }; + sock.ev.on("messages.upsert", handleMessagesUpsert); - sock.ev.on( - "connection.update", - (update: Partial) => { + const handleConnectionUpdate = ( + update: Partial, + ) => { try { if (update.connection === "close") { const status = getStatusCode(update.lastDisconnect?.error); @@ -320,12 +324,22 @@ export async function monitorWebInbox(options: { error: err, }); } - }, - ); + }; + sock.ev.on("connection.update", handleConnectionUpdate); return { close: async () => { try { + if (typeof sock.ev.off === "function") { + sock.ev.off("messages.upsert", handleMessagesUpsert); + sock.ev.off("connection.update", handleConnectionUpdate); + } else { + sock.ev.removeListener?.("messages.upsert", handleMessagesUpsert); + sock.ev.removeListener?.( + "connection.update", + handleConnectionUpdate, + ); + } sock.ws?.close(); } catch (err) { logVerbose(`Socket close failed: ${String(err)}`);