Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): keep live chat rows when a background refetch lands
Yudhi Armyndharis5aee525f01a7
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsindex 7137bd6ab..ba988f26d 100644--- a/dashboard/src/pages/Chats.test.ts+++ b/dashboard/src/pages/Chats.test.ts@@ -864,6 +864,78 @@ test('a socket reconnect refetches the chat list so the sidebar shows what arrivassert.equal(countFetchCalls('GET', chatsPath), 2);});+test('a message that lands while a reconnect refetch is out survives the older snapshot', async () => {+ const { screen, act, waitFor } = rtl;+ resetFetchCalls();+ renderChats();+ await screen.findByText('Alice');++ // The refetch's snapshot was built before the live message below reached the gateway.+ let release!: () => void;+ const gate = new Promise<void>(resolve => {+ release = resolve;+ });+ chatsResponder = () => gate.then(() => jsonResponse([CHAT, CHAT_2]));+ const socket = lastSocket();+ assert.ok(socket, 'expected the page to have opened a socket');+ act(() => socket.receive('disconnect', 'transport close'));+ act(() => socket.receive('connect'));+ await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats`), 2));++ act(() =>+ socket.receive('message', {+ type: 'event',+ timestamp: new Date(1_700_002_000_000).toISOString(),+ payload: {+ event: 'message.received',+ sessionId: SESSION.id,+ data: {+ id: 'wamid.live.refetch',+ chatId: CHAT.id,+ from: CHAT.id,+ to: 'me',+ body: 'while the list reloads',+ type: 'text',+ fromMe: false,+ timestamp: 1_700_001_000,+ },+ },+ }),+ );+ await screen.findByText('while the list reloads');++ release();+ await flush();+ await flush();+ assert.ok(screen.queryByText('while the list reloads'), 'the older snapshot replaced the live preview');+ assert.ok(screen.queryByLabelText('3 unread messages'), 'the older snapshot dropped the live unread count');+});++test('a row a send stamped with the browser clock does not outrank a later reconnect snapshot', async () => {+ const { screen, fireEvent, within, act, waitFor } = rtl;+ const { container } = renderChats();+ await screen.findByText('Main (15551234567)');+ fireEvent.click(await screen.findByText('Alice'));+ await within(container.querySelector('.room-messages') as HTMLElement).findByText('hello from alice');++ // The send stamps Alice's row with the browser clock, far ahead of the fixture timestamps, and no+ // echo arrives to replace that stamp with the gateway's.+ fireEvent.change(screen.getByPlaceholderText('Type a message...'), { target: { value: 'hello back' } });+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));+ await waitFor(() => assert.ok(findFetchCall('POST', `/api/sessions/${SESSION.id}/messages/send-text`)));++ chatsResponder = () =>+ Promise.resolve(+ jsonResponse([{ ...CHAT, lastMessage: 'a reply after the send', timestamp: 1_700_000_800 }, CHAT_2]),+ );+ const socket = lastSocket();+ assert.ok(socket, 'expected the page to have opened a socket');+ act(() => socket.receive('disconnect', 'transport close'));+ act(() => socket.receive('connect'));++ await screen.findByText('a reply after the send');+});+test('a socket reconnect keeps the open chat read instead of badging it with the gap count', async () => {const { screen, fireEvent, within, act, waitFor } = rtl;const { container } = renderChats();diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 6fb3e894e..fdc3f904f 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -315,6 +315,11 @@ export function Chats() {const chatsRequestRef = useRef(0);const chatsAppliedRef = useRef(0);const chatsSessionRef = useRef('');+ // The session whose list `chats` holds, which a switch leaves on screen until the new list lands.+ const listedSessionRef = useRef('');+ // The newest request number out when a live frame last moved each chat's row. A send stamps its row+ // with the browser clock, so only this, not a newer timestamp, shows a row changed after a refetch left.+ const liveRowsRef = useRef(new Map<string, number>());const loadChats = useCallback(async (sessionId: string, { background = false } = {}): Promise<boolean> => {if (!sessionId) return false;@@ -329,14 +334,27 @@ export function Chats() {const data = await sessionApi.getChats(sessionId);if (stale()) return overtaken();chatsAppliedRef.current = request;- const sorted = [...data].sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));- setChats(sorted);+ // A live frame can move a row past the snapshot a background refetch was built from while it is+ // out. That row is kept, or its preview and unread badge would roll back until the next message.+ const moved = (id: string) => (liveRowsRef.current.get(id) ?? 0) >= request;+ const merge = background && listedSessionRef.current === sessionId;+ listedSessionRef.current = sessionId;+ setChats(prev => {+ const live = new Map(merge ? prev.map(c => [c.id, c] as const) : []);+ return data+ .map(c => {+ const row = live.get(c.id);+ return row && moved(c.id) && (row.timestamp || 0) > (c.timestamp || 0) ? row : c;+ })+ .sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));+ });return true;} catch (err) {if (stale()) return overtaken();// A background refetch only refreshes summaries: keep the list it would have replaced.if (background) return false;showLoadError('chats.errors.loadChats', err);+ listedSessionRef.current = sessionId;setChats([]);return false;} finally {@@ -456,6 +474,7 @@ export function Chats() {// A location message's body is the (multi-KB) base64 map thumbnail; show a label instead.locationLabel: `📍 ${t('chats.media.location')}`,};+ liveRowsRef.current.set(newMsg.chatId, chatsRequestRef.current);const { needsSidebarRefetch } = applyIncomingToChatList(chatsRef.current, newMsg, listOptions);setChats(prevChats => applyIncomingToChatList(prevChats, newMsg, listOptions).chats);if (needsSidebarRefetch) {