Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): stop refetching the chat list twice for an unknown chat
Yudhi Armyndharisf6d95a135cb5
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex bfbbfa0e5..69ab0adc0 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback, useRef, useMemo, useLayoutEffect } frimport { useQuery, useQueryClient } from '@tanstack/react-query';import { Trans, useTranslation } from 'react-i18next';import { nextReconnectState } from '../utils/reconnectState';+import { applyIncomingToChatList, promoteChatWithSnippet } from '../utils/chatList';import {Search,Send,@@ -657,36 +658,22 @@ export function Chats() {if (!newMsg.fromMe) onMessageAppended('incoming');}- // Update sidebar chat list+ // Update sidebar chat list. The refetch is REPORTED by the reducer and fired below, never from+ // inside the updater: React double-invokes updaters under StrictMode, so a side effect in there+ // ran twice for every message arriving in a chat the sidebar does not have.+ let needsSidebarRefetch = false;setChats(prevChats => {- const chatIndex = prevChats.findIndex(c => c.id === newMsg.chatId);- if (chatIndex === -1) {- // A message for a chat not in the sidebar. Suppress the refetch ONLY for an outgoing echo- // addressed as `@lid`: a LID-migrated contact echoes back `@lid` while the user sent to- // `@c.us`, and the sent bubble is already reconciled in the active chat, so refetching on- // every such send just churns the chat list (#583 R2). Incoming messages and ordinary- // outgoing sends to a genuinely new chat still refetch so the sidebar stays complete.- const isMigratedEcho = newMsg.fromMe && (newMsg.chatId?.endsWith('@lid') ?? false);- if (!isMigratedEcho) {- void loadChats(selectedSessionId);- }- return prevChats;- }-- const updatedChats = [...prevChats];- const targetChat = { ...updatedChats[chatIndex] };- // A location message's body is the (multi-KB) base64 map thumbnail; show a label instead.- targetChat.lastMessage = newMsg.type === 'location' ? `π ${t('chats.media.location')}` : newMsg.body;- targetChat.timestamp = newMsg.timestamp;-- if (!newMsg.fromMe && (!activeChat || activeChat.id !== targetChat.id)) {- targetChat.unreadCount = (targetChat.unreadCount || 0) + 1;- }-- updatedChats.splice(chatIndex, 1);- updatedChats.unshift(targetChat);- return updatedChats;+ const result = applyIncomingToChatList(prevChats, newMsg, {+ activeChatId: activeChat?.id,+ // A location message's body is the (multi-KB) base64 map thumbnail; show a label instead.+ locationLabel: `π ${t('chats.media.location')}`,+ });+ needsSidebarRefetch = result.needsSidebarRefetch;+ return result.chats;});+ if (needsSidebarRefetch) {+ void loadChats(selectedSessionId);+ }},[selectedSessionId, activeChat, loadChats, markChatRead, appendMessage, onMessageAppended, t],);@@ -1166,17 +1153,9 @@ export function Chats() {});// Update sidebar chat list (move active chat to the top with the new snippet)- setChats(prevChats => {- const chatIndex = prevChats.findIndex(c => c.id === activeChat.id);- if (chatIndex === -1) return prevChats;- const updatedChats = [...prevChats];- const target = { ...updatedChats[chatIndex] };- target.lastMessage = currentAttachment ? `[${currentAttachment.mimetype.split('/')[0]}]` : textToSend;- target.timestamp = Math.floor(Date.now() / 1000);- updatedChats.splice(chatIndex, 1);- updatedChats.unshift(target);- return updatedChats;- });+ const snippet = currentAttachment ? `[${currentAttachment.mimetype.split('/')[0]}]` : textToSend;+ const sentAt = Math.floor(Date.now() / 1000);+ setChats(prevChats => promoteChatWithSnippet(prevChats, activeChat.id, snippet, sentAt));} catch (err) {showErrorToast(t('chats.errors.send'), err instanceof Error ? err.message : undefined);updateMessage(selectedSessionId, activeChat.id, tempId, { status: 'failed' });diff --git a/dashboard/src/utils/chatList.test.ts b/dashboard/src/utils/chatList.test.tsnew file mode 100644index 000000000..d38c35672--- /dev/null+++ b/dashboard/src/utils/chatList.test.ts@@ -0,0 +1,120 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { applyIncomingToChatList, promoteChatWithSnippet, type ChatListEntry } from './chatList.ts';++const chat = (id: string, over: Partial<ChatListEntry> = {}): ChatListEntry => ({+ id,+ lastMessage: 'old',+ timestamp: 100,+ ...over,+});++const LOCATION = 'π Location';++test('an arriving message moves its chat to the top and refreshes the snippet', () => {+ const before = [chat('[email protected]'), chat('[email protected]')];++ const { chats, needsSidebarRefetch } = applyIncomingToChatList(+ before,+ { chatId: '[email protected]', body: 'hi', type: 'text', timestamp: 200 },+ { locationLabel: LOCATION },+ );++ assert.equal(needsSidebarRefetch, false);+ assert.deepEqual(+ chats.map(c => c.id),+ ['[email protected]', '[email protected]'],+ );+ assert.equal(chats[0].lastMessage, 'hi');+ assert.equal(chats[0].timestamp, 200);+ assert.deepEqual(before.map(c => c.id), ['[email protected]', '[email protected]'], 'input is not mutated');+});++test('a location message shows the label, never its base64 body', () => {+ const { chats } = applyIncomingToChatList(+ [chat('[email protected]')],+ { chatId: '[email protected]', body: 'data:image/jpeg;base64,AAAAβ¦', type: 'location', timestamp: 200 },+ { locationLabel: LOCATION },+ );++ assert.equal(chats[0].lastMessage, LOCATION);+});++test('unread increments only for an incoming message in a chat that is not open', () => {+ const incomingElsewhere = applyIncomingToChatList(+ [chat('[email protected]', { unreadCount: 2 })],+ { chatId: '[email protected]', body: 'hi', timestamp: 200 },+ { activeChatId: '[email protected]', locationLabel: LOCATION },+ );+ assert.equal(incomingElsewhere.chats[0].unreadCount, 3);++ const incomingOnScreen = applyIncomingToChatList(+ [chat('[email protected]', { unreadCount: 2 })],+ { chatId: '[email protected]', body: 'hi', timestamp: 200 },+ { activeChatId: '[email protected]', locationLabel: LOCATION },+ );+ assert.equal(incomingOnScreen.chats[0].unreadCount, 2);++ const ownSend = applyIncomingToChatList(+ [chat('[email protected]', { unreadCount: 2 })],+ { chatId: '[email protected]', body: 'hi', timestamp: 200, fromMe: true },+ { activeChatId: '[email protected]', locationLabel: LOCATION },+ );+ assert.equal(ownSend.chats[0].unreadCount, 2);+});++test('an unknown chat asks for a refetch, and leaves the list alone', () => {+ const before = [chat('[email protected]')];++ const { chats, needsSidebarRefetch } = applyIncomingToChatList(+ before,+ { chatId: '[email protected]', body: 'hi', timestamp: 200 },+ { locationLabel: LOCATION },+ );++ assert.equal(needsSidebarRefetch, true);+ assert.equal(chats, before);+});++test('a LID-migrated own-send echo does NOT ask for a refetch (#583 R2)', () => {+ // The user sent to @c.us; the contact echoes back @lid. The bubble is already reconciled in the+ // open chat, so refetching on every such send only churns the sidebar.+ const { needsSidebarRefetch } = applyIncomingToChatList(+ [chat('[email protected]')],+ { chatId: '628111@lid', body: 'hi', timestamp: 200, fromMe: true },+ { locationLabel: LOCATION },+ );++ assert.equal(needsSidebarRefetch, false);+});++test('an INCOMING message from an unknown @lid chat still asks for a refetch', () => {+ // The suppression is scoped to own-send echoes; a genuinely new inbound chat must appear.+ const { needsSidebarRefetch } = applyIncomingToChatList(+ [chat('[email protected]')],+ { chatId: '628111@lid', body: 'hi', timestamp: 200, fromMe: false },+ { locationLabel: LOCATION },+ );++ assert.equal(needsSidebarRefetch, true);+});++test('promoteChatWithSnippet moves the sent-into chat to the top', () => {+ const before = [chat('[email protected]'), chat('[email protected]')];++ const after = promoteChatWithSnippet(before, '[email protected]', '[image]', 999);++ assert.deepEqual(+ after.map(c => c.id),+ ['[email protected]', '[email protected]'],+ );+ assert.equal(after[0].lastMessage, '[image]');+ assert.equal(after[0].timestamp, 999);+ assert.deepEqual(before.map(c => c.id), ['[email protected]', '[email protected]'], 'input is not mutated');+});++test('promoteChatWithSnippet leaves an unknown chat alone rather than inventing a row', () => {+ const before = [chat('[email protected]')];++ assert.equal(promoteChatWithSnippet(before, '[email protected]', 'x', 1), before);+});diff --git a/dashboard/src/utils/chatList.ts b/dashboard/src/utils/chatList.tsnew file mode 100644index 000000000..adc7d18b1--- /dev/null+++ b/dashboard/src/utils/chatList.ts@@ -0,0 +1,92 @@+/**+ * Sidebar chat-list reducers.+ *+ * These decide how the conversation list reorders when a message arrives or is sent: which chat moves+ * to the top, what snippet it shows, and when an unread badge increments. They were inline `setChats`+ * updaters, which made them unreachable from a test and let a side effect sit inside one β see+ * `applyIncomingToChatList` below.+ *+ * Generic over the chat shape so the caller keeps its own `Chat` type; only the four fields these+ * reducers actually touch are constrained.+ */++export interface ChatListEntry {+ id: string;+ lastMessage?: string;+ timestamp?: number;+ unreadCount?: number;+}++interface IncomingMessageLike {+ chatId?: string;+ body?: string;+ type?: string;+ timestamp?: number;+ fromMe?: boolean;+}++export interface ChatListUpdate<T> {+ chats: T[];+ /**+ * The message belongs to a chat the sidebar does not have, so the caller should refetch.+ *+ * Returned rather than acted on: this used to be a `void loadChats(...)` INSIDE the `setChats`+ * updater, and React double-invokes updaters under StrictMode, so every message for an unknown chat+ * refetched the list twice. A reducer that reports what is needed lets the caller fire it once,+ * outside.+ */+ needsSidebarRefetch: boolean;+}++/**+ * Fold an arriving message into the sidebar: move its chat to the top, refresh the snippet and+ * timestamp, and bump the unread badge when the chat is not the one on screen.+ *+ * `locationLabel` is passed in because the snippet for a location message must not be its body β that+ * is a multi-kilobyte base64 map thumbnail β and the label itself is localised at the callsite.+ */+export function applyIncomingToChatList<T extends ChatListEntry>(+ chats: T[],+ msg: IncomingMessageLike,+ opts: { activeChatId?: string; locationLabel: string },+): ChatListUpdate<T> {+ const index = chats.findIndex(c => c.id === msg.chatId);+ if (index === -1) {+ // Suppress the refetch ONLY for an outgoing echo addressed as `@lid`: a LID-migrated contact+ // echoes back `@lid` while the user sent to `@c.us`, and the sent bubble is already reconciled in+ // the active chat, so refetching on every such send just churns the chat list (#583 R2). Incoming+ // messages and ordinary outgoing sends to a genuinely new chat still refetch.+ const isMigratedEcho = (msg.fromMe ?? false) && (msg.chatId?.endsWith('@lid') ?? false);+ return { chats, needsSidebarRefetch: !isMigratedEcho };+ }++ const updated = [...chats];+ const target = { ...updated[index] };+ target.lastMessage = msg.type === 'location' ? opts.locationLabel : msg.body;+ target.timestamp = msg.timestamp;+ if (!msg.fromMe && opts.activeChatId !== target.id) {+ target.unreadCount = (target.unreadCount || 0) + 1;+ }+ updated.splice(index, 1);+ updated.unshift(target);+ return { chats: updated, needsSidebarRefetch: false };+}++/**+ * Move a chat to the top with a new snippet after the user sends into it. Unknown chat = no change:+ * the send path never creates a sidebar row, it only promotes one that exists.+ */+export function promoteChatWithSnippet<T extends ChatListEntry>(+ chats: T[],+ chatId: string,+ snippet: string,+ timestamp: number,+): T[] {+ const index = chats.findIndex(c => c.id === chatId);+ if (index === -1) return chats;+ const updated = [...chats];+ const target = { ...updated[index], lastMessage: snippet, timestamp };+ updated.splice(index, 1);+ updated.unshift(target);+ return updated;+}