Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(dashboard): load older chat history as you scroll up

JuanGalzerano040bb30237f3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 02219ebaf..9ff6fcbe7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
engine, for large accounts whose reads fail with `Runtime.callFunctionOn timed out`. Unset keeps
Puppeteer's own budget, so nothing changes for a deployment that does not set it. The gateway
refuses to boot on `0` or on a value above 2147483647; see docs/12 for when to reach for it.
+- The dashboard chat room loads older history as you scroll up, instead of stopping at the newest
+ 100 messages. Pages are requested by the number of DB rows already fetched — not by the length of
+ the rendered thread, which also carries engine-history items — so no row is skipped between
+ pages, and the reading position is held when a page is prepended rather than jumping.
### Changed
diff --git a/dashboard/src/components/chats/ChatComposer.tsx b/dashboard/src/components/chats/ChatComposer.tsx
index 27e65d298..7368119ba 100644
--- a/dashboard/src/components/chats/ChatComposer.tsx
+++ b/dashboard/src/components/chats/ChatComposer.tsx
@@ -3,10 +3,10 @@ import { useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { Loader2, Paperclip, Send, Smile, X } from 'lucide-react';
import { messageApi, type Chat, type MessageType } from '../../services/api';
-import { mergeOrAppend, type ChatMessageView } from '../../utils/chatMessages';
+import { type ChatMessageView } from '../../utils/chatMessages';
import { promoteChatWithSnippet } from '../../utils/chatList';
import { buildMediaSendPayload, buildOptimisticMetadata, quotedIdOf } from '../../utils/composerSend';
-import { messagesQueryKey, useChatMessagesActions } from '../../hooks/useChatMessages';
+import { messagesQueryKey, useChatMessagesActions, upsertCachedMessage } from '../../hooks/useChatMessages';
import { useRole } from '../../hooks/useRole';
import { useToast } from '../../hooks/useToast';
import type { ScrollDirection } from '../../utils/scrollDecision';
@@ -235,22 +235,13 @@ function ChatComposer({
// payload (a Baileys API send echoes only a marker), so dropping the placeholder would erase
// the attachment's base64 and leave a bare "📎 Media" bubble until the next refetch.
const sendKey = messagesQueryKey(selectedSessionId, activeChat.id);
- queryClient.setQueryData<ChatMessageView[]>(sendKey, (prev = []) => {
- const reconciled: ChatMessageView = {
- ...tempMessage,
- id: result.messageId,
- waMessageId: result.messageId,
- status: 'sent',
- };
- const echoAlreadyAdded = prev.some(m => m.id === result.messageId || m.waMessageId === result.messageId);
- if (echoAlreadyAdded) {
- return mergeOrAppend(
- prev.filter(m => m.id !== tempId),
- reconciled,
- );
- }
- return prev.map(m => (m.id === tempId ? reconciled : m));
- });
+ const reconciled: ChatMessageView = {
+ ...tempMessage,
+ id: result.messageId,
+ waMessageId: result.messageId,
+ status: 'sent',
+ };
+ upsertCachedMessage(queryClient, sendKey, reconciled, { dropId: tempId });
// Update sidebar chat list (move active chat to the top with the new snippet)
const snippet = currentAttachment ? `[${currentAttachment.mimetype.split('/')[0]}]` : textToSend;
diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsx
index 8fb71abd0..a7825d3f7 100644
--- a/dashboard/src/components/chats/ChatThread.tsx
+++ b/dashboard/src/components/chats/ChatThread.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { ChevronDown, CornerUpLeft, Loader2, MessageSquare, Smile, Trash2 } from 'lucide-react';
import { sessionApi, type Chat } from '../../services/api';
import { getMediaSrc, senderKey, type ChatMessageView } from '../../utils/chatMessages';
+import { shouldFetchOlderMessages } from '../../utils/scrollDecision';
import MessageBody from './MessageBody';
// Stable per-sender colour for group message labels, like WhatsApp gives each participant a colour.
@@ -23,6 +24,10 @@ interface ChatThreadProps {
loadingMessages: boolean;
messagesError: boolean;
messagesContainerRef: RefObject<HTMLDivElement | null>;
+ /** Whether an older page of this chat's history exists. */
+ hasMoreMessages: boolean;
+ loadingOlderMessages: boolean;
+ onLoadOlderMessages: () => void;
onMediaLoad: () => void;
onOpenImage: (messageId: string) => void;
onReply: (message: ChatMessageView) => void;
@@ -41,6 +46,9 @@ function ChatThread({
loadingMessages,
messagesError,
messagesContainerRef,
+ hasMoreMessages,
+ loadingOlderMessages,
+ onLoadOlderMessages,
onMediaLoad,
onOpenImage,
onReply,
@@ -98,9 +106,20 @@ function ChatThread({
useEffect(() => {
const el = messagesContainerRef.current;
if (!el) return undefined;
- const onScroll = () => {
+ const onScroll = (event?: Event) => {
// 120px gap = a couple of message bubbles before counting as "scrolled up".
setShowJumpToBottom(el.scrollHeight - el.scrollTop - el.clientHeight > 120);
+ const geometry = { scrollTop: el.scrollTop, scrollHeight: el.scrollHeight, clientHeight: el.clientHeight };
+ if (
+ shouldFetchOlderMessages({
+ isUserScroll: Boolean(event),
+ geometry,
+ hasMore: hasMoreMessages,
+ isFetching: loadingOlderMessages,
+ })
+ ) {
+ onLoadOlderMessages();
+ }
};
onScroll(); // sync initial position (e.g. saved restore landed above the bottom)
el.addEventListener('scroll', onScroll, { passive: true });
@@ -141,6 +160,14 @@ function ChatThread({
<ChevronDown size={22} />
</button>
)}
+ {/* Older-page spinner. A sibling above the thread rather than a wrapper around it, so it
+ renders over the oldest bubble without the list moving. */}
+ {loadingOlderMessages && !loadingMessages && (
+ <div className="messages-loading-older">
+ <Loader2 className="animate-spin" size={18} />
+ <span>{t('chats.loadingOlderMessages')}</span>
+ </div>
+ )}
{loadingMessages ? (
<div className="messages-loading">
<Loader2 className="animate-spin" size={32} />
diff --git a/dashboard/src/hooks/useChatMessages.ts b/dashboard/src/hooks/useChatMessages.ts
index 25ccaca07..588421561 100644
--- a/dashboard/src/hooks/useChatMessages.ts
+++ b/dashboard/src/hooks/useChatMessages.ts
@@ -1,13 +1,19 @@
-import { useQuery, useQueryClient, type UseQueryResult } from '@tanstack/react-query';
+import {
+ useInfiniteQuery,
+ useQueryClient,
+ type InfiniteData,
+ type UseInfiniteQueryResult,
+} from '@tanstack/react-query';
+import type { QueryClient } from '@tanstack/react-query';
import {
mergeChatMessages,
mapEngineHistoryMessage,
- mergeOrAppend,
updateMessageById,
removeMessageById,
type ChatMessageView,
-} from '../utils/chatMessages';
-import { sessionApi } from '../services/api';
+} from '../utils/chatMessages.ts';
+import { upsertIntoPages, nextMessagePageParam, type MessagePage } from '../utils/messagePages.ts';
+import { sessionApi } from '../services/api.ts';
export type MessagesQueryKey = readonly ['messages', string, string];
@@ -15,36 +21,108 @@ export function messagesQueryKey(sessionId: string, chatId: string): MessagesQue
return ['messages', sessionId, chatId] as const;
}
+/** How many DB rows one page asks for. The gateway clamps `limit` to 100, so this is its maximum. */
+export const MESSAGE_PAGE_SIZE = 100;
+
+export type MessagesData = InfiniteData<MessagePage>;
+
/**
- * Fetch messages for one (sessionId, chatId) and keep them cached (staleTime: Infinity); realtime
- * updates flow through useChatMessagesActions, not refetches. Engine history is fetched WITHOUT media
- * to keep the cache small — a single 50 MiB message would otherwise sit in heap as base64 (held twice
- * as a `data:` URI). Recent media still renders from the DB copy (which wins in mergeChatMessages);
- * older history media shows the omitted placeholder. Live/DB payloads that do arrive are additionally
- * bounded per slice: mergeChatMessages/mergeOrAppend run the result through capMediaPayloads, which
- * strips the oldest base64 beyond MEDIA_PAYLOAD_CACHE_LIMIT so a long media-heavy session can't grow
- * the tab's heap without bound. Cache eviction happens 5 min after the chat stops being observed
- * (gcTime), so browsing several media-rich chats doesn't accumulate large slices.
+ * Fetch a chat's messages a page at a time, newest page first, cached at staleTime: Infinity;
+ * realtime updates flow through useChatMessagesActions, not refetches.
+ *
+ * Engine history comes with the first page only — it is a one-shot backfill of a thread the gateway
+ * never captured, with no cursor to page through. Fetched without media to keep the cache small; the
+ * DB copy wins in mergeChatMessages, so recent media still renders.
*/
-export function useChatMessages(sessionId: string, chatId: string | null): UseQueryResult<ChatMessageView[], Error> {
- return useQuery<ChatMessageView[], Error>({
+export function useChatMessages(
+ sessionId: string,
+ chatId: string | null,
+): UseInfiniteQueryResult<ChatMessageView[], Error> {
+ return useInfiniteQuery<MessagePage, Error, ChatMessageView[], MessagesQueryKey, number>({
queryKey: messagesQueryKey(sessionId, chatId ?? ''),
- queryFn: async () => {
+ initialPageParam: 0,
+ queryFn: async ({ pageParam }) => {
+ const wantsHistory = pageParam === 0;
const [dbRes, historyRes] = await Promise.allSettled([
- sessionApi.getChatMessages(sessionId, chatId!, 100),
- sessionApi.getChatHistory(sessionId, chatId!, 100, false),
+ sessionApi.getChatMessages(sessionId, chatId!, MESSAGE_PAGE_SIZE, pageParam),
+ wantsHistory ? sessionApi.getChatHistory(sessionId, chatId!, 100, false) : Promise.resolve([]),
]);
- if (dbRes.status === 'rejected' && historyRes.status === 'rejected') throw dbRes.reason;
- const dbMessages = dbRes.status === 'fulfilled' ? dbRes.value.messages : [];
+ // Only the first page may fall back to history alone; an older page has no second source, so a
+ // rejected DB read there is a real failure and must surface rather than resolve to an empty
+ // page that would read as "no more messages".
+ if (dbRes.status === 'rejected' && (!wantsHistory || historyRes.status === 'rejected')) throw dbRes.reason;
+ const db = dbRes.status === 'fulfilled' ? dbRes.value : { messages: [], total: 0 };
const history = historyRes.status === 'fulfilled' ? historyRes.value.map(mapEngineHistoryMessage) : [];
- return mergeChatMessages(dbMessages, history);
+ return { db: db.messages, history, total: db.total };
},
+ getNextPageParam: (_lastPage, allPages) => nextMessagePageParam(allPages),
+ // Consumers keep seeing one flat chronological list; paging stays inside the cache.
+ select: data =>
+ mergeChatMessages(
+ data.pages.flatMap(page => page.db),
+ data.pages.flatMap(page => page.history),
+ ),
enabled: Boolean(sessionId && chatId),
staleTime: Infinity,
gcTime: 5 * 60 * 1000,
});
}
+/**
+ * Apply a list transform to every cached page. Both arrays are transformed: a message the gateway
+ * never persisted exists only in `history`, so touching `db` alone would drop its edits and deletes.
+ */
+function mapCachedMessages(
+ queryClient: QueryClient,
+ key: MessagesQueryKey,
+ transform: (list: ChatMessageView[]) => ChatMessageView[],
+): void {
+ queryClient.setQueryData<MessagesData>(key, old =>
+ old === undefined
+ ? undefined
+ : {
+ ...old,
+ pages: old.pages.map(page => ({
+ ...page,
+ db: transform(page.db),
+ history: transform(page.history),
+ })),
+ },
+ );
+}
+
+/**
+ * Edit one chat's cached messages from outside this module, without the call site having to know
+ * the paged cache shape: it hands over a plain list transform.
+ */
+export function updateCachedMessages(
+ queryClient: QueryClient,
+ key: MessagesQueryKey,
+ transform: (list: ChatMessageView[]) => ChatMessageView[],
+): void {
+ mapCachedMessages(queryClient, key, transform);
+}
+
+/**
+ * Insert or merge one message, optionally dropping an optimistic placeholder by id.
+ *
+ * Which page receives it matters: `mergeOrAppend` appends when it finds no match, so running it
+ * over every page would add a copy to each one. The message is merged into the page that already
+ * holds it, and only lands on the newest page when no page does.
+ */
+export function upsertCachedMessage(
+ queryClient: QueryClient,
+ key: MessagesQueryKey,
+ incoming: ChatMessageView,
+ options: { dropId?: string } = {},
+): void {
+ queryClient.setQueryData<MessagesData>(key, old =>
+ old === undefined || old.pages.length === 0
+ ? undefined
+ : { ...old, pages: upsertIntoPages(old.pages, incoming, options.dropId) },
+ );
+}
+
/**
* Mutation helpers that write directly to the React Query cache. Use these
* from the WebSocket subscriber, the optimistic-send flow, and ACK handlers
@@ -55,21 +133,16 @@ export function useChatMessagesActions() {
return {
appendMessage(sessionId: string, chatId: string, msg: ChatMessageView) {
- // Only append to a slice that already exists (a chat that has been opened). Do NOT seed a slice
- // for a never-opened chat: with staleTime: Infinity that phantom slice would be "fresh", so
- // opening the chat would skip the full-history queryFn and show only this one message (truncated
- // history). Returning undefined from the updater is a no-op when there is no cached data.
- qc.setQueryData<ChatMessageView[]>(messagesQueryKey(sessionId, chatId), old =>
- old === undefined ? undefined : mergeOrAppend(old, msg),
- );
+ // Only writes to a slice that already exists. Seeding one for a never-opened chat would be
+ // "fresh" under staleTime: Infinity, so opening the chat would skip the queryFn and show this
+ // message alone.
+ upsertCachedMessage(qc, messagesQueryKey(sessionId, chatId), msg);
},
updateMessage(sessionId: string, chatId: string, id: string, patch: Partial<ChatMessageView>) {
- qc.setQueryData<ChatMessageView[]>(messagesQueryKey(sessionId, chatId), (old = []) =>
- updateMessageById(old, id, patch),
- );
+ mapCachedMessages(qc, messagesQueryKey(sessionId, chatId), list => updateMessageById(list, id, patch));
},
removeMessage(sessionId: string, chatId: string, id: string) {
- qc.setQueryData<ChatMessageView[]>(messagesQueryKey(sessionId, chatId), (old = []) => removeMessageById(old, id));
+ mapCachedMessages(qc, messagesQueryKey(sessionId, chatId), list => removeMessageById(list, id));
},
};
}
diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.ts
index 1cbdcfb2a..2a05455da 100644
--- a/dashboard/src/hooks/useChatScrollPosition.ts
+++ b/dashboard/src/hooks/useChatScrollPosition.ts
@@ -76,6 +76,8 @@ export function useChatScrollPosition(
containerRef: RefObject<HTMLDivElement | null>;
onMessageAppended: (direction: ScrollDirection) => void;
onMediaLoad: () => void;
+ /** Call before prepending older messages; call the result after, to hold the reading position. */
+ onOlderMessagesPrepended: () => () => void;
} {
const containerRef = useRef<HTMLDivElement | null>(null);
const scrollMap = useRef<Map<string, number>>(new Map());
@@ -193,5 +195,24 @@ export function useChatScrollPosition(
});
}, [pinToBottom, writeScrollTop]);
- return { containerRef, onMessageAppended, onMediaLoad };
+ // Older messages are prepended ABOVE the viewport, so the content the user is reading is pushed
+ // down by however much taller the thread just got. Left alone the thread appears to jump backwards
+ // at the exact moment the user asked for more. Call this immediately BEFORE the prepend to capture
+ // the geometry, then call the returned function right AFTER it to add the delta back.
+ //
+ // Deliberately not the pin/restore machinery above: those write an ABSOLUTE scrollTop, which is
+ // wrong here — the target is only known relative to how much the prepend grew scrollHeight.
+ const onOlderMessagesPrepended = useCallback(() => {
+ const el = containerRef.current;
+ if (!el) return () => undefined;
+ const before = el.scrollHeight;
+ const top = el.scrollTop;
+ return () => {
+ const cur = containerRef.current;
+ if (!cur) return;
+ writeScrollTop(cur, top + (cur.scrollHeight - before));
+ };
+ }, [writeScrollTop]);
+
+ return { containerRef, onMessageAppended, onMediaLoad, onOlderMessagesPrepended };
}
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 3323755ad..dbc97cd2a 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -90,6 +90,7 @@
"unreadBadge_few": "{{count}} رسائل غير مقروءة",
"unreadBadge_many": "{{count}} رسالة غير مقروءة",
"loadingMessages": "جارٍ تحميل الرسائل...",
+ "loadingOlderMessages": "جارٍ تحميل الرسائل الأقدم...",
"noMessagesInChat": "لا توجد رسائل بعد. أرسل الرسالة الأولى للبدء!",
"downloadDocument": "تنزيل المستند",
"actions": {
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index 4542b1e67..bec5f0e08 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -87,6 +87,7 @@
"unreadBadge": "{{count}} ungelesene Nachricht",
"unreadBadge_other": "{{count}} ungelesene Nachrichten",
"loadingMessages": "Nachrichten werden geladen...",
+ "loadingOlderMessages": "Ältere Nachrichten werden geladen...",
"noMessagesInChat": "Noch keine Nachrichten. Sende die erste Nachricht, um zu beginnen!",
"downloadDocument": "Dokument herunterladen",
"actions": {
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index f4b323e61..56d9a206e 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -87,6 +87,7 @@
"unreadBadge": "{{count}} unread message",
"unreadBadge_other": "{{count}} unread messages",
"loadingMessages": "Loading messages...",
+ "loadingOlderMessages": "Loading older messages...",
"noMessagesInChat": "No messages yet. Send the first message to get started!",
"downloadDocument": "Download document",
"actions": {
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index a6c7c347c..69bfde018 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -87,6 +87,7 @@
"unreadBadge": "{{count}} mensaje sin leer",
"unreadBadge_other": "{{count}} mensajes sin leer",
"loadingMessages": "Cargando mensajes...",
+ "loadingOlderMessages": "Cargando mensajes anteriores...",
"noMessagesInChat": "Aún no hay mensajes. ¡Envía el primero para empezar!",
"downloadDocument": "Descargar documento",
"actions": {
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 1b80b8ed9..83a46f46a 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -87,6 +87,7 @@
"unreadBadge": "{{count}} message non lu",
"unreadBadge_other": "{{count}} messages non lus",
"loadingMessages": "Chargement des messages...",
+ "loadingOlderMessages": "Chargement des messages plus anciens...",
"noMessagesInChat": "Aucun message pour le moment. Envoyez le premier message pour commencer !",
"downloadDocument": "Télécharger le document",
"actions": {
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index e82baf561..01d79ac4a 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -89,6 +89,7 @@
"unreadBadge_two": "שתי הודעות שלא נקראו",
"unreadBadge_many": "{{count}} הודעות שלא נקראו",
"loadingMessages": "טוען הודעות...",
+ "loadingOlderMessages": "טוען הודעות ישנות יותר...",
"noMessagesInChat": "אין הודעות עדיין. שלח את ההודעה הראשונה כדי להתחיל!",
"downloadDocument": "הורדת מסמך",
"actions": {
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 8196a0c5b..2d69a344b 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -87,6 +87,7 @@
"unreadBadge": "{{count}} messaggio non letto",
"unreadBadge_other": "{{count}} messaggi non letti",
"loadingMessages": "Caricamento messaggi...",
+ "loadingOlderMessages": "Caricamento messaggi precedenti...",
"noMessagesInChat": "Ancora nessun messaggio. Invia il primo messaggio per iniziare!",
"downloadDocument": "Scarica documento",
"actions": {
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index 41ba479cf..b3fb1736a 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -87,6 +87,7 @@
"unreadBadge": "읽지 않은 메시지 {{count}}개",
"unreadBadge_other": "읽지 않은 메시지 {{count}}개",
"loadingMessages": "메시지 불러오는 중...",
+ "loadingOlderMessages": "이전 메시지 불러오는 중...",
"noMessagesInChat": "아직 메시지가 없습니다. 첫 메시지를 보내 대화를 시작하세요!",
"downloadDocument": "문서 다운로드",
"actions": {
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index 01f28ece6..340a2a722 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -87,6 +87,7 @@
"unreadBadge": "{{count}} mensagem não lida",
"unreadBadge_other": "{{count}} mensagens não lidas",
"loadingMessages": "Carregando mensagens...",
+ "loadingOlderMessages": "Carregando mensagens anteriores...",
"noMessagesInChat": "Ainda não há mensagens. Envie a primeira para começar!",
"downloadDocument": "Baixar documento",
"actions": {
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index df2eae15e..f0f5c6d79 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -87,6 +87,7 @@
"unreadBadge": "{{count}} చదవని సందేశం",
"unreadBadge_other": "{{count}} చదవని సందేశాలు",
"loadingMessages": "సందేశాలను లోడ్ చేస్తోంది...",
+ "loadingOlderMessages": "పాత సందేశాలను లోడ్ చేస్తోంది...",
"noMessagesInChat": "ఇంకా సందేశాలు లేవు. ప్రారంభించడానికి మొదటి సందేశాన్ని పంపండి!",
"downloadDocument": "డాక్యుమెంట్‌ను డౌన్‌లోడ్ చేయి",
"actions": {
diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.json
index 4a3700198..256ff1dde 100644
--- a/dashboard/src/i18n/locales/tr.json
+++ b/dashboard/src/i18n/locales/tr.json
@@ -87,6 +87,7 @@
"unreadBadge": "{{count}} okunmamış mesaj",
"unreadBadge_other": "{{count}} okunmamış mesaj",
"loadingMessages": "Mesajlar yükleniyor...",
+ "loadingOlderMessages": "Daha eski mesajlar yükleniyor...",
"noMessagesInChat": "Henüz mesaj yok. Başlamak için ilk mesajı gönderin!",
"downloadDocument": "Belgeyi indir",
"actions": {
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 3441f04c0..02b56f9d8 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -87,6 +87,7 @@
"unreadBadge": "{{count}} 条未读消息",
"unreadBadge_other": "{{count}} 条未读消息",
"loadingMessages": "正在加载消息...",
+ "loadingOlderMessages": "正在加载更早的消息...",
"noMessagesInChat": "暂无消息。发送第一条消息即可开始!",
"downloadDocument": "下载文档",
"actions": {
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index ad176393f..6869928aa 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -87,6 +87,7 @@
"unreadBadge": "{{count}} 條未讀訊息",
"unreadBadge_other": "{{count}} 條未讀訊息",
"loadingMessages": "正在載入訊息...",
+ "loadingOlderMessages": "正在載入較舊的訊息...",
"noMessagesInChat": "尚無訊息。傳送第一則訊息即可開始!",
"downloadDocument": "下載文件",
"actions": {
diff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.css
index 755b0aa34..450aeff41 100644
--- a/dashboard/src/pages/Chats.css
+++ b/dashboard/src/pages/Chats.css
@@ -487,6 +487,19 @@
gap: 0.75rem;
}
+/* Sits inline above the oldest bubble, so unlike .messages-loading it must not take the flex
+ remainder — that would push the thread out of view while an older page loads. */
+.chats-page .messages-loading-older {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 auto;
+ color: var(--text-muted);
+ font-size: 0.8125rem;
+ gap: 0.5rem;
+ padding: 0.5rem 0;
+}
+
.chats-page .messages-empty {
display: flex;
flex-direction: column;
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 8cac4e899..f78602354 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -34,7 +34,12 @@ import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useToast } from '../hooks/useToast';
import { PageHeader } from '../components/PageHeader';
import { GlobalSearch } from '../components/GlobalSearch';
-import { useChatMessages, useChatMessagesActions, messagesQueryKey } from '../hooks/useChatMessages';
+import {
+ useChatMessages,
+ useChatMessagesActions,
+ messagesQueryKey,
+ updateCachedMessages,
+} from '../hooks/useChatMessages';
import { useChannelMessages } from '../hooks/useChannelMessages';
import { useContactStatuses } from '../hooks/useContactStatuses';
import { useChatScrollPosition } from '../hooks/useChatScrollPosition';
@@ -173,6 +178,9 @@ export function Chats() {
data: messages = [],
isLoading: loadingMessages,
isError: messagesError,
+ hasNextPage: hasMoreMessages,
+ isFetchingNextPage: loadingOlderMessages,
+ fetchNextPage,
} = useChatMessages(selectedSessionId, activeChat?.id ?? null);
const { appendMessage, updateMessage } = useChatMessagesActions();
const queryClient = useQueryClient();
@@ -224,8 +232,28 @@ export function Chats() {
containerRef: messagesContainerRef,
onMessageAppended,
onMediaLoad,
+ onOlderMessagesPrepended,
} = useChatScrollPosition(activeChat?.id ?? null, messages.length > 0);
+ // Capture the scroll geometry before the older page lands, and restore it once the new bubbles are
+ // in the DOM — otherwise the thread jumps backwards by the height of whatever was just prepended.
+ // A layout effect, not a callback on the fetch promise: the promise settles before React has
+ // committed the new rows, so restoring there would measure the old height.
+ const restoreOlderScrollRef = useRef<(() => void) | null>(null);
+ const handleLoadOlderMessages = useCallback(() => {
+ restoreOlderScrollRef.current = onOlderMessagesPrepended();
+ void fetchNextPage();
+ }, [fetchNextPage, onOlderMessagesPrepended]);
+
+ // Also keyed on the loading flag so a page that adds nothing still clears the pending restore
+ // instead of leaving it to fire on an unrelated later render.
+ useLayoutEffect(() => {
+ const restore = restoreOlderScrollRef.current;
+ if (!restore || loadingOlderMessages) return;
+ restoreOlderScrollRef.current = null;
+ restore();
+ }, [messages.length, loadingOlderMessages]);
+
// Batch profile-picture fetch for the visible chat list — ONE request for the whole sidebar
// (per-row queries burst the per-IP throttle into 429s). Sorted-key cached 1h; rows fall back
// to the generic icon for ids that resolve null.
@@ -607,7 +635,7 @@ export function Chats() {
// Deep-merge metadata.reactions so existing media / quotedMessage on metadata survive.
const key = messagesQueryKey(selectedSessionId, activeChat.id);
- queryClient.setQueryData<ChatMessageView[]>(key, (old = []) =>
+ updateCachedMessages(queryClient, key, old =>
old.map(m => {
if (m.id === msg.id || m.waMessageId === msg.id) {
const metadata = m.metadata || {};
@@ -924,6 +952,9 @@ export function Chats() {
loadingMessages={loadingMessages}
messagesError={messagesError}
messagesContainerRef={messagesContainerRef}
+ hasMoreMessages={Boolean(hasMoreMessages)}
+ loadingOlderMessages={loadingOlderMessages}
+ onLoadOlderMessages={handleLoadOlderMessages}
onMediaLoad={onMediaLoad}
onOpenImage={messageId => {
const idx = imageMedia.findIndex(x => x.id === messageId);
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index a0fded4cc..e612d34a5 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -787,9 +787,12 @@ export const sessionApi = {
method: 'POST',
body: JSON.stringify({ chatId }),
}),
- getChatMessages: (id: string, chatId: string, limit = 100) =>
+ // `offset` counts DB rows already fetched for this chat, never rendered rows: the thread merges
+ // these with engine history, so paging by the merged length would skip DB rows. `total` is the
+ // full row count for the chat (getManyAndCount), which is what says whether an older page exists.
+ getChatMessages: (id: string, chatId: string, limit = 100, offset = 0) =>
request<{ messages: ChatMessage[]; total: number }>(
- `/sessions/${id}/messages?chatId=${encodeURIComponent(chatId)}&limit=${limit}`,
+ `/sessions/${id}/messages?chatId=${encodeURIComponent(chatId)}&limit=${limit}&offset=${offset}`,
),
// Live history straight from WhatsApp (bypasses the DB) — backfills a thread the gateway never
// captured, e.g. a freshly paired session whose persisted store is still empty.
diff --git a/dashboard/src/utils/messagePages.test.ts b/dashboard/src/utils/messagePages.test.ts
new file mode 100644
index 000000000..e808aa849
--- /dev/null
+++ b/dashboard/src/utils/messagePages.test.ts
@@ -0,0 +1,98 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { dbRowsFetched, nextMessagePageParam, upsertIntoPages, type MessagePage } from './messagePages.ts';
+import type { ChatMessageView } from './chatMessages.ts';
+
+const msg = (id: string, extra: Partial<ChatMessageView> = {}): ChatMessageView =>
+ ({
+ id,
+ waMessageId: id,
+ chatId: 'c1',
+ body: id,
+ type: 'text',
+ direction: 'incoming',
+ status: 'read',
+ timestamp: 1,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ ...extra,
+ }) as ChatMessageView;
+
+const page = (db: ChatMessageView[], total: number, history: ChatMessageView[] = []): MessagePage => ({
+ db,
+ history,
+ total,
+});
+
+test('the cursor counts DB rows, not the rendered merge', () => {
+ // The regression this guards: engine history inflates the rendered list, so paging by its length
+ // would ask for an offset past rows the DB read never returned — silently skipping them.
+ const pages = [page([msg('a'), msg('b')], 10, [msg('h1'), msg('h2'), msg('h3')])];
+
+ assert.equal(dbRowsFetched(pages), 2);
+ assert.equal(nextMessagePageParam(pages), 2);
+});
+
+test('the cursor accumulates across pages', () => {
+ const pages = [page([msg('a'), msg('b')], 10), page([msg('c')], 10)];
+
+ assert.equal(nextMessagePageParam(pages), 3);
+});
+
+test('paging stops once the chat total is covered', () => {
+ assert.equal(nextMessagePageParam([page([msg('a'), msg('b')], 2)]), undefined);
+});
+
+test('paging stops on an empty chat rather than asking for offset 0 forever', () => {
+ assert.equal(nextMessagePageParam([page([], 0)]), undefined);
+});
+
+test('a live message lands on the newest page', () => {
+ const pages = [page([msg('new')], 3), page([msg('old')], 3)];
+
+ const result = upsertIntoPages(pages, msg('live'));
+
+ assert.deepEqual(
+ result[0].db.map(m => m.id),
+ ['new', 'live'],
+ );
+ assert.deepEqual(
+ result[1].db.map(m => m.id),
+ ['old'],
+ );
+});
+
+test('a message already held by an older page is merged there, not duplicated', () => {
+ // mergeOrAppend appends when it finds no match, so running it over every page would leave one
+ // copy per page. An ack for an old message must update it where it lives.
+ const pages = [page([msg('new')], 3), page([msg('old', { status: 'sent' })], 3)];
+
+ const result = upsertIntoPages(pages, msg('old', { status: 'read' }));
+
+ assert.equal(result.flatMap(p => p.db).filter(m => m.id === 'old').length, 1);
+ assert.equal(result[0].db.length, 1);
+ assert.equal(result[1].db[0].status, 'read');
+});
+
+test('an optimistic placeholder is dropped from whichever page holds it', () => {
+ const pages = [page([msg('tmp-1')], 2)];
+
+ const result = upsertIntoPages(pages, msg('real-1'), 'tmp-1');
+
+ assert.deepEqual(
+ result.flatMap(p => p.db).map(m => m.id),
+ ['real-1'],
+ );
+});
+
+test('the placeholder is dropped even when the echo already arrived on its own', () => {
+ // The send response and the realtime echo race: if the echo won, the placeholder must still go,
+ // and its payload must fold into the echo rather than leaving two bubbles.
+ const pages = [page([msg('tmp-1'), msg('real-1')], 2)];
+
+ const result = upsertIntoPages(pages, msg('real-1', { status: 'sent' }), 'tmp-1');
+
+ assert.deepEqual(
+ result.flatMap(p => p.db).map(m => m.id),
+ ['real-1'],
+ );
+});
diff --git a/dashboard/src/utils/messagePages.ts b/dashboard/src/utils/messagePages.ts
new file mode 100644
index 000000000..8e6ba307d
--- /dev/null
+++ b/dashboard/src/utils/messagePages.ts
@@ -0,0 +1,52 @@
+import { mergeOrAppend, type ChatMessageView } from './chatMessages.ts';
+
+/**
+ * One fetched slice of a chat's history. `db` and `history` stay separate because the page cursor is
+ * the number of DB rows fetched, and merging first loses that count — the merged list adds engine
+ * history items and drops the duplicates between the two sources.
+ */
+export interface MessagePage {
+ db: ChatMessageView[];
+ history: ChatMessageView[];
+ /** Total DB rows for this chat (getManyAndCount) — says whether an older page exists. */
+ total: number;
+}
+
+/** DB rows fetched across every page so far — the offset the next page asks for. */
+export function dbRowsFetched(pages: MessagePage[]): number {
+ return pages.reduce((count, page) => count + page.db.length, 0);
+}
+
+/**
+ * Offset of the next older page, or undefined once the chat's rows are covered.
+ *
+ * Counting DB rows, not merged/rendered ones: the merged list carries engine-history items too, so
+ * paging by its length would step the cursor past rows that were never read.
+ */
+export function nextMessagePageParam(pages: MessagePage[]): number | undefined {
+ const fetched = dbRowsFetched(pages);
+ const total = pages[pages.length - 1]?.total ?? 0;
+ return fetched < total ? fetched : undefined;
+}
+
+const messageKey = (m: ChatMessageView): string => m.waMessageId ?? m.id;
+
+/**
+ * Insert or merge one message, optionally dropping an optimistic placeholder by id.
+ *
+ * Which page receives it matters: `mergeOrAppend` appends when it finds no match, so running it over
+ * every page would add a copy to each one. The message is merged into the page that already holds
+ * it, and only lands on the newest page when no page does.
+ */
+export function upsertIntoPages(pages: MessagePage[], incoming: ChatMessageView, dropId?: string): MessagePage[] {
+ const trimmed = dropId
+ ? pages.map(page => ({
+ ...page,
+ db: page.db.filter(m => m.id !== dropId),
+ history: page.history.filter(m => m.id !== dropId),
+ }))
+ : pages;
+ const target = trimmed.findIndex(page => page.db.some(m => messageKey(m) === messageKey(incoming)));
+ const index = target === -1 ? 0 : target;
+ return trimmed.map((page, i) => (i === index ? { ...page, db: mergeOrAppend(page.db, incoming) } : page));
+}
diff --git a/dashboard/src/utils/scrollDecision.test.ts b/dashboard/src/utils/scrollDecision.test.ts
index 38c458be2..c35398da8 100644
--- a/dashboard/src/utils/scrollDecision.test.ts
+++ b/dashboard/src/utils/scrollDecision.test.ts
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { decideScroll, type ScrollGeometry } from './scrollDecision.ts';
+import { decideScroll, shouldFetchOlderMessages, type ScrollGeometry } from './scrollDecision.ts';
const at = (scrollTop: number, scrollHeight = 1000, clientHeight = 500): ScrollGeometry => ({
scrollTop,
@@ -37,3 +37,69 @@ test('custom threshold overrides default', () => {
// gap = 200, threshold 300 → bottom
assert.equal(decideScroll('incoming', at(300), 300), 'bottom');
});
+
+// --- shouldFetchOlderMessages -------------------------------------------------
+// A long thread: 7045px of content in a 148px viewport, the shape measured in the browser.
+const longThread = { scrollTop: 20, scrollHeight: 7045, clientHeight: 148 };
+
+test('reading back to the top pulls the next older page', () => {
+ assert.equal(
+ shouldFetchOlderMessages({ isUserScroll: true, geometry: longThread, hasMore: true, isFetching: false }),
+ true,
+ );
+});
+
+test('the render-time sync call never pages, however close to the top it reports', () => {
+ // The regression: the thread's listener also runs on every render to refresh the jump button, and
+ // a freshly opened room reports scrollTop 0 there. Paging from it cascaded — each page re-rendered
+ // and asked for the next, so opening a chat pulled its whole history in one burst.
+ assert.equal(
+ shouldFetchOlderMessages({
+ isUserScroll: false,
+ geometry: { scrollTop: 0, scrollHeight: 7045, clientHeight: 148 },
+ hasMore: true,
+ isFetching: false,
+ }),
+ false,
+ );
+});
+
+test('a thread shorter than its viewport never pages', () => {
+ // Same cascade from the other side: it sits at scrollTop 0 permanently.
+ assert.equal(
+ shouldFetchOlderMessages({
+ isUserScroll: true,
+ geometry: { scrollTop: 0, scrollHeight: 300, clientHeight: 300 },
+ hasMore: true,
+ isFetching: false,
+ }),
+ false,
+ );
+});
+
+test('a fetch already in flight is not doubled', () => {
+ // Scroll events arrive per frame, so one gesture would otherwise fire a burst.
+ assert.equal(
+ shouldFetchOlderMessages({ isUserScroll: true, geometry: longThread, hasMore: true, isFetching: true }),
+ false,
+ );
+});
+
+test('nothing older left means no request', () => {
+ assert.equal(
+ shouldFetchOlderMessages({ isUserScroll: true, geometry: longThread, hasMore: false, isFetching: false }),
+ false,
+ );
+});
+
+test('mid-thread scrolling does not page', () => {
+ assert.equal(
+ shouldFetchOlderMessages({
+ isUserScroll: true,
+ geometry: { scrollTop: 3000, scrollHeight: 7045, clientHeight: 148 },
+ hasMore: true,
+ isFetching: false,
+ }),
+ false,
+ );
+});
diff --git a/dashboard/src/utils/scrollDecision.ts b/dashboard/src/utils/scrollDecision.ts
index 46ec66c2b..0cd116b03 100644
--- a/dashboard/src/utils/scrollDecision.ts
+++ b/dashboard/src/utils/scrollDecision.ts
@@ -30,3 +30,30 @@ export function decideScroll(
const gap = geometry.scrollHeight - geometry.scrollTop - geometry.clientHeight;
return gap < nearBottomThreshold ? 'bottom' : 'preserve';
}
+
+/** How close to the top counts as "reading back through the thread". */
+const NEAR_TOP_THRESHOLD = 100;
+
+/**
+ * Decide whether reaching the top of the thread should pull the next older page.
+ *
+ * `isUserScroll` is load-bearing, not defensive. The thread's listener also runs a sync call on
+ * every render to refresh the scroll-to-bottom button, and a freshly opened room reports
+ * `scrollTop` 0 there — which reads as "at the top". Paging from that call cascaded: each page
+ * re-rendered, re-ran the sync call at scrollTop 0 and asked for the next one, so opening a chat
+ * pulled its whole history in one burst instead of a page at a time.
+ *
+ * The scrollable check covers the same shape from the other side: a thread shorter than its
+ * viewport sits at scrollTop 0 permanently and would page forever on any stray event.
+ */
+export function shouldFetchOlderMessages(args: {
+ isUserScroll: boolean;
+ geometry: ScrollGeometry;
+ hasMore: boolean;
+ isFetching: boolean;
+}): boolean {
+ const { isUserScroll, geometry, hasMore, isFetching } = args;
+ if (!isUserScroll || !hasMore || isFetching) return false;
+ if (geometry.scrollHeight <= geometry.clientHeight) return false;
+ return geometry.scrollTop < NEAR_TOP_THRESHOLD;
+}
diff --git a/docs/17-dashboard-design.md b/docs/17-dashboard-design.md
index c6e720b51..406caeda6 100644
--- a/docs/17-dashboard-design.md
+++ b/docs/17-dashboard-design.md
@@ -102,7 +102,8 @@ a non-admin hitting the path falls through to the `*` redirect.
/ → Dashboard (overview + charts)
/sessions → Sessions (create / start / stop / QR / delete)
/chats → Chats (Chats / Channels / Status tabs; chat list + message thread live via
- WebSocket; read-only channel feed on whatsapp-web.js)
+ WebSocket; thread pages older history in on scroll-up; read-only channel
+ feed on whatsapp-web.js)
/webhooks → Webhooks (per-session webhook endpoints)
/templates → Message Templates
/message-tester → Message Tester (ad-hoc send-* + check-number)
@@ -402,6 +403,13 @@ Chat-specific pieces live one level down in `components/chats/`: `MessageBody` (
formatting + link detection) and `MediaLightbox` (the media viewer, built on
`yet-another-react-lightbox`).
+The message thread is paged. `useChatMessages` is a `useInfiniteQuery` whose cursor is the number
+of DB rows fetched so far, not the length of the rendered list — the thread also carries engine
+history and drops the duplicates between the two, so its length is not an offset the gateway would
+agree with. Reaching the top requests the next page; the reading position is held across the
+prepend rather than jumping. Both rules are pure functions with tests: `utils/messagePages.ts` for
+the cursor, `shouldFetchOlderMessages` in `utils/scrollDecision.ts` for when to ask.
+
Pages live under `dashboard/src/pages/`, each as a `*.tsx` + `*.css` pair (e.g. `Sessions.tsx` +
`Sessions.css`). Pages are lazy-loaded in `App.tsx` via `React.lazy` + `Suspense`.