Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): refetch a cached chat thread after a session switch

Yudhi Armyndharisca23bf76a850
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index 9b36863da..d4d13ca4e 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -1437,6 +1437,45 @@ test('a staged reply is kept on reopening its chat and dropped when a different
);
});
+test('a chat reopened after switching sessions and back fetches its thread again', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ twoSessions = true;
+ chatsResponder = sessionId => Promise.resolve(jsonResponse(sessionId === SESSION.id ? [CHAT] : [CHAT_2]));
+ // The stub folds session 2's routes onto session 1's, so the thread reads are counted before that.
+ const threadPath = `/api/sessions/${SESSION.id}/messages?chatId=${encodeURIComponent(CHAT.id)}&`;
+ let threadFetches = 0;
+ const stub = globalThis.fetch;
+ globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
+ if (String(input).includes(threadPath)) threadFetches++;
+ return stub(input, init);
+ }) as typeof fetch;
+ try {
+ const { container } = renderChats();
+ const selectSession = (id: string) =>
+ fireEvent.change(container.querySelector('select.session-selector') as HTMLSelectElement, {
+ target: { value: id },
+ });
+
+ await screen.findByText('Main (15551234567)');
+ fireEvent.click(await screen.findByText('Alice'));
+ await within(container.querySelector('.room-messages') as HTMLElement).findByText('hello from alice');
+ assert.equal(threadFetches, 1);
+
+ // Session 1's events are not delivered while session 2 is selected, so its cached threads may
+ // have missed messages by the time it is selected again.
+ selectSession(SESSION_2.id);
+ await screen.findByText('Carol');
+ await waitFor(() => assert.equal(screen.queryByText('Alice'), null));
+ selectSession(SESSION.id);
+ fireEvent.click(await screen.findByText('Alice'));
+ await within(container.querySelector('.room-messages') as HTMLElement).findByText('hello from alice');
+ await waitFor(() => assert.equal(threadFetches, 2, 'the cached thread was shown without a refetch'));
+ } finally {
+ globalThis.fetch = stub;
+ twoSessions = false;
+ }
+});
+
test('a staged reply is dropped when another session is opened', async () => {
const { screen, fireEvent, within, waitFor } = rtl;
twoSessions = true;
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 78b3f3f52..def3c6a4a 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -622,11 +622,11 @@ export function Chats() {
);
const { isConnected, connectionFailed, reconnect, subscribe, unsubscribe } = useWebSocket(wsEvents);
- // A transient WebSocket gap means message.received/ack/revoke events were missed, and the chat
- // cache uses staleTime: Infinity so it won't refetch on its own. On a reconnect (isConnected
- // false→true after a prior connect), invalidate the active session's messages so the thread the
- // gap left stale refreshes. A failed feed counts as a gap even if it never connected, so the
- // banner's retry refreshes too. The transition logic is unit-tested in utils/reconnectState.
+ // A transient WebSocket gap means message.received/ack/revoke/status events were missed. On a
+ // reconnect (isConnected false→true after a prior connect), refresh what the gap left stale; the
+ // threads are refreshed by the subscribe effect below, which runs on every connect. A failed feed
+ // counts as a gap even if it never connected, so the banner's retry refreshes too. The transition
+ // logic is unit-tested in utils/reconnectState.
const reconnectHadConnected = useRef(false);
const reconnectWasDisconnected = useRef(false);
const activeChatId = activeChat?.id;
@@ -640,7 +640,6 @@ export function Chats() {
reconnectHadConnected.current = decision.hadConnected;
reconnectWasDisconnected.current = decision.wasDisconnected;
if (decision.invalidate) {
- queryClient.invalidateQueries({ queryKey: ['messages', selectedSessionId] });
// Statuses are live now (status.received): a story posted during the socket gap would
// otherwise stay invisible until a focus refetch.
queryClient.invalidateQueries({ queryKey: ['contact-statuses', selectedSessionId] });
@@ -673,11 +672,15 @@ export function Chats() {
'message.edited',
'status.received',
]);
+ // The threads cache at staleTime: Infinity, and events for this session were not delivered before
+ // this subscribe: after a mount, a session switch or a reconnect, a cached thread may miss some.
+ // Mark them stale so the open one refetches and the others do when opened.
+ void queryClient.invalidateQueries({ queryKey: ['messages', selectedSessionId] });
return () => {
unsubscribe(selectedSessionId);
};
}
- }, [selectedSessionId, isConnected, subscribe, unsubscribe]);
+ }, [selectedSessionId, isConnected, subscribe, unsubscribe, queryClient]);
// 4. Message history is fetched by useChatMessages (React Query). The active-chat side effects
// (mark-as-read + clear sidebar unread badge) live in a small effect below.