Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): mark a chat read on reconnect once the list loads

Yudhi Armyndharis5338079e3e57
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index eae32217f..7137bd6ab 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -889,6 +889,131 @@ test('a socket reconnect keeps the open chat read instead of badging it with the
assert.ok(findFetchCall('POST', `/api/sessions/${SESSION.id}/chats/read`), 'the gap messages were not marked read');
});
+test('a reconnect whose refetch fails while the engine starts sends no mark-as-read', async () => {
+ const { screen, fireEvent, within, act } = 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');
+ await new Promise(resolve => setTimeout(resolve, 1_000));
+ resetFetchCalls();
+
+ // After a backend restart the socket is back before the engine: the session's routes answer 409.
+ chatsResponder = () =>
+ Promise.resolve(jsonResponse({ statusCode: 409, message: 'Engine not ready', code: 'ENGINE_NOT_READY' }, 409));
+ 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 new Promise(resolve => setTimeout(resolve, 1_000));
+ assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats`), 1);
+ assert.ok(
+ !findFetchCall('POST', `/api/sessions/${SESSION.id}/chats/read`),
+ 'a mark-as-read went out while the engine was starting',
+ );
+});
+
+test('a reconnect refetch that settles after the open chat was left keeps its unread count', 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');
+ await new Promise(resolve => setTimeout(resolve, 1_000));
+ resetFetchCalls();
+
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ chatsResponder = () =>
+ gate.then(() => jsonResponse([{ ...CHAT, unreadCount: 4, lastMessage: 'sent after leaving' }, 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`), 1));
+
+ // The user moves on to Carol before the refetch lands; Alice's new message was never seen.
+ fireEvent.click(await screen.findByText('Carol'));
+ release();
+ await screen.findByText('sent after leaving');
+ await new Promise(resolve => setTimeout(resolve, 1_000));
+ assert.ok(screen.queryByLabelText('4 unread messages'), 'the chat the user left lost its unread count');
+ assert.ok(
+ !fetchCalls.some(
+ c =>
+ c.method === 'POST' &&
+ c.path === `/api/sessions/${SESSION.id}/chats/read` &&
+ (c.body as { chatId?: string } | undefined)?.chatId === CHAT.id,
+ ),
+ 'the chat the user left was marked read',
+ );
+});
+
+test('a reconnect refetch overtaken by a newer list still marks the open chat read', 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');
+ await new Promise(resolve => setTimeout(resolve, 1_000));
+ resetFetchCalls();
+
+ // The reconnect refetch stays out while a live frame for an unlisted chat fires a second one, which
+ // lands first. Both snapshots count Alice's gap messages, although her chat is open.
+ const DAVE: Chat = { ...CHAT_2, id: '[email protected]', name: 'Dave', timestamp: 1_700_000_900 };
+ const snapshot = [{ ...CHAT, unreadCount: 4, lastMessage: 'sent during the gap' }, CHAT_2, DAVE];
+ let releaseFirst!: () => void;
+ const firstGate = new Promise<void>(resolve => {
+ releaseFirst = resolve;
+ });
+ let served = 0;
+ chatsResponder = () =>
+ ++served === 1 ? firstGate.then(() => jsonResponse(snapshot)) : Promise.resolve(jsonResponse(snapshot));
+ 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`), 1));
+
+ 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.dave',
+ chatId: DAVE.id,
+ from: DAVE.id,
+ to: 'me',
+ body: 'dave says hi',
+ type: 'text',
+ fromMe: false,
+ timestamp: 1_700_001_900,
+ },
+ },
+ }),
+ );
+ await screen.findByText('sent during the gap');
+
+ releaseFirst();
+ await new Promise(resolve => setTimeout(resolve, 1_000));
+ assert.ok(!screen.queryByLabelText('4 unread messages'), 'the open chat was badged with the gap count');
+ assert.ok(
+ fetchCalls.some(
+ c =>
+ c.method === 'POST' &&
+ c.path === `/api/sessions/${SESSION.id}/chats/read` &&
+ (c.body as { chatId?: string } | undefined)?.chatId === CHAT.id,
+ ),
+ 'the gap messages in the open chat were not marked read',
+ );
+});
+
test("a reconnect refetch that settles after a session switch leaves the new session's unread badge", async () => {
const { screen, fireEvent, within, act, waitFor } = rtl;
twoSessions = true;
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 78a66730d..6fb3e894e 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -316,23 +316,29 @@ export function Chats() {
const chatsAppliedRef = useRef(0);
const chatsSessionRef = useRef('');
const loadChats = useCallback(
- async (sessionId: string, { background = false } = {}) => {
- if (!sessionId) return;
+ async (sessionId: string, { background = false } = {}): Promise<boolean> => {
+ if (!sessionId) return false;
const request = ++chatsRequestRef.current;
chatsSessionRef.current = sessionId;
const stale = () => sessionId !== chatsSessionRef.current || request < chatsAppliedRef.current;
+ // A stale answer for the session still selected was overtaken by a newer list that has applied,
+ // so this session's list on screen is as fresh as this call's would have been.
+ const overtaken = () => sessionId === chatsSessionRef.current;
try {
if (!background) setLoadingChats(true);
const data = await sessionApi.getChats(sessionId);
- if (stale()) return;
+ if (stale()) return overtaken();
chatsAppliedRef.current = request;
const sorted = [...data].sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
setChats(sorted);
+ return true;
} catch (err) {
+ if (stale()) return overtaken();
// A background refetch only refreshes summaries: keep the list it would have replaced.
- if (stale() || background) return;
+ if (background) return false;
showLoadError('chats.errors.loadChats', err);
setChats([]);
+ return false;
} finally {
// Only the call that raised the spinner clears it: a background refetch settling first would
// otherwise uncover the previous session's list while the switch's own load is still out.
@@ -399,8 +405,10 @@ export function Chats() {
// Synced in a layout effect: a socket frame handled after the list commits but before passive
// effects flush would otherwise see the previous list, miss the chat and refetch the whole list.
const chatsRef = useRef(chats);
+ const activeChatIdRef = useRef<string | undefined>(undefined);
useLayoutEffect(() => {
chatsRef.current = chats;
+ activeChatIdRef.current = activeChat?.id;
});
const handleIncomingMessage = useCallback(
(event: { sessionId: string; message: Record<string, unknown> }) => {
@@ -611,16 +619,18 @@ export function Chats() {
queryClient.invalidateQueries({ queryKey: ['contact-statuses', selectedSessionId] });
// The sidebar list is local state, so previews, unread counts and chats started during the gap
// only show after a refetch. Background mode keeps the current list on screen meanwhile.
- // The open chat's gap messages are read on screen: mark them read and keep its row at zero,
- // since the snapshot still counts them (the same rule a live frame and opening a chat follow).
+ // The open chat's gap messages are read on screen, so once the refetch has applied this session's
+ // list and the chat is still open, mark it read and zero its row, since the snapshot still counts
+ // them (the same rule a live frame and opening a chat follow). An applied list also means the engine
+ // answers again: after a backend restart it may still be starting, and a read sent then fails. A
+ // newer list for this session that overtook the refetch counts as applied. A refetch that failed
+ // with no newer list applied, or a session switch, sends nothing; a chat the user left keeps its
+ // count.
const readChatId = canWrite ? activeChatId : undefined;
- if (readChatId) markChatRead(readChatId);
- // The zeroing waits for the refetch, by when another session's list may be on screen; like a send's
- // promote, it applies only while the list is still this session's.
- void loadChats(selectedSessionId, { background: true }).then(() => {
- if (readChatId && chatsSessionRef.current === selectedSessionId) {
- setChats(prev => prev.map(c => (c.id === readChatId ? { ...c, unreadCount: 0 } : c)));
- }
+ void loadChats(selectedSessionId, { background: true }).then(applied => {
+ if (!applied || !readChatId || activeChatIdRef.current !== readChatId) return;
+ markChatRead(readChatId);
+ setChats(prev => prev.map(c => (c.id === readChatId ? { ...c, unreadCount: 0 } : c)));
});
}
}, [isConnected, connectionFailed, selectedSessionId, queryClient, loadChats, activeChatId, canWrite, markChatRead]);