diff --git a/src/Socket/chats.ts b/src/Socket/chats.ts index c8d35641..b0a0b0dc 100644 --- a/src/Socket/chats.ts +++ b/src/Socket/chats.ts @@ -1309,6 +1309,10 @@ export const makeChatsSocket = (config: SocketConfig) => { // Automatic chat merge: notify consumers about LID→PN mapping // This allows ZPRO and other consumers to merge/rename chats accordingly + // Collect all merge notifications to emit in a single batch + const mergeNotifications: ChatUpdate[] = [] + const mergedAt = Date.now() + for (const mapping of mappings) { const lidUser = jidNormalizedUser(mapping.lid) const pnUser = jidNormalizedUser(mapping.pn) @@ -1316,20 +1320,34 @@ export const makeChatsSocket = (config: SocketConfig) => { if (lidUser && pnUser && lidUser !== pnUser) { logger.debug( { lid: lidUser, pn: pnUser }, - 'emitting chat update for LID→PN merge notification' + 'collected chat update for LID→PN merge notification' ) - // Emit chat update indicating this chat should be merged/renamed from LID to PN - ev.emit('chats.update', [ - { - id: pnUser, - merged: true, - previousId: lidUser, - mergedAt: Date.now() - } - ]) + mergeNotifications.push({ + id: pnUser, + merged: true, + previousId: lidUser, + mergedAt + }) } } + + // Emit single batch of merge notifications for better performance + if (mergeNotifications.length > 0) { + logger.debug( + { count: mergeNotifications.length }, + 'emitting batch of chat merge notifications' + ) + ev.emit('chats.update', mergeNotifications) + } + + // Log warning if some mappings failed to store + if (result.errors > 0) { + logger.warn( + { errors: result.errors, total: mappings.length, notified: mergeNotifications.length }, + 'some LID-PN mappings failed to store, but merge notifications were sent' + ) + } } catch (error) { logger.warn({ count: mappings.length, error }, 'Failed to store LID-PN mappings') }