Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): correct scroll anchoring, error handling, and cursor drift in paged messages
JuanGalzeranoe55bdd219c4e
diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsxindex a7825d3f7..6fb434265 100644--- a/dashboard/src/components/chats/ChatThread.tsx+++ b/dashboard/src/components/chats/ChatThread.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useState, type RefObject } from 'react';import { useTranslation } from 'react-i18next';-import { ChevronDown, CornerUpLeft, Loader2, MessageSquare, Smile, Trash2 } from 'lucide-react';+import { AlertCircle, 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';@@ -160,12 +160,26 @@ 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 && (+ {/* Older-page spinner, or the failure in its place. An in-flow sibling before the thread, not+ an overlay — it pushes the oldest bubble down, which is why useChatScrollPosition reads+ this container's height at REQUEST time (before this renders), not on whichever commit+ happens to change it first. Shown whenever there IS a thread to sit above — including a+ failed older-page fetch with messages already loaded, which must not fall through to the+ full-screen error below: that would replace the loaded thread with a placeholder,+ collapsing the scroll container so the failed page can never be retried by scrolling. */}+ {!loadingMessages && (loadingOlderMessages || (messagesError && messages.length > 0)) && (<div className="messages-loading-older">- <Loader2 className="animate-spin" size={18} />- <span>{t('chats.loadingOlderMessages')}</span>+ {loadingOlderMessages ? (+ <>+ <Loader2 className="animate-spin" size={18} />+ <span>{t('chats.loadingOlderMessages')}</span>+ </>+ ) : (+ <>+ <AlertCircle size={18} />+ <span>{t('chats.loadOlderMessagesError')}</span>+ </>+ )}</div>)}{loadingMessages ? (@@ -173,7 +187,7 @@ function ChatThread({<Loader2 className="animate-spin" size={32} /><span>{t('chats.loadingMessages')}</span></div>- ) : messagesError ? (+ ) : messagesError && messages.length === 0 ? (<div className="messages-empty"><MessageSquare size={32} /><span>{t('chats.loadMessagesError')}</span>diff --git a/dashboard/src/hooks/useChatMessages.ts b/dashboard/src/hooks/useChatMessages.tsindex 93f99c2ac..e04c5ab40 100644--- a/dashboard/src/hooks/useChatMessages.ts+++ b/dashboard/src/hooks/useChatMessages.ts@@ -22,7 +22,12 @@ export function messagesQueryKey(sessionId: string, chatId: string): MessagesQuereturn ['messages', sessionId, chatId] as const;}-/** How many DB rows one page asks for. The gateway clamps `limit` to 100, so this is its maximum. */+/**+ * How many DB rows one page asks for. The gateway clamps `limit` to 100+ * (`message.service.ts`: `Math.min(Math.max(Math.trunc(rawLimit), 1), 100)`), so this is its+ * maximum. Termination assumes the clamp holds: a page short of THIS value is read as the last one+ * (see `nextMessagePageParam`), so a lower clamp on the server would end paging after page one.+ */export const MESSAGE_PAGE_SIZE = 100;export type MessagesData = InfiniteData<MessagePage>;@@ -84,18 +89,14 @@ export function useChatMessages(// infiniteQueryBehavior reads `oldPages` in onFetch), so its result overwrites anything written// meanwhile — and at staleTime: Infinity no refetch brings it back. An optimistic send during// that window would leave the thread for good. Replay those writes on top of the landed page.- const { isFetching } = query;- // Leaving this chat drops anything still queued for it rather than holding the closures (and any- // base64 payload they captured) for the tab's life. Nothing is lost: the writes describe- // server-side events, so reopening the chat refetches a thread that already contains them.//- // Its own effect, keyed only on the chat: putting the cleanup on the effect below — which- // re-runs on both edges of every fetch — would run it on the true→false edge, deleting the queue- // moments before that same run replayed it.- useEffect(() => {- const key = messagesQueryKey(sessionId, chatId ?? '');- return () => discardWritesLostToFetch(key);- }, [sessionId, chatId]);+ // The queue is deliberately NOT discarded when this hook unmounts (switching chats, say) — the+ // in-flight fetch it is waiting on is not cancelled, so it still lands and overwrites the cache+ // later regardless of whether anything is mounted to see it. Discarding here only threw the write+ // away before that landing, since staleTime: Infinity means reopening the chat does not refetch to+ // recover it. Left queued, remounting the same chat re-runs this effect, and the identity check in+ // replayWritesLostToFetch still finds the landed page's value different from what was recorded.+ const { isFetching } = query;useEffect(() => {if (isFetching) return;replayWritesLostToFetch(queryClient, messagesQueryKey(sessionId, chatId ?? ''));@@ -157,11 +158,6 @@ export function replayWritesLostToFetch(queryClient: QueryClient, key: MessagesQ);}-/** Forget anything still queued for a chat, e.g. because the user moved to another one. */-export function discardWritesLostToFetch(key: MessagesQueryKey): void {- writesLostToFetch.delete(pendingKey(key));-}-/*** 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.diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex dbc97cd2a..8f1c2491a 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -91,6 +91,7 @@"unreadBadge_many": "{{count}} رسالة غير مقروءة","loadingMessages": "جارٍ تحميل الرسائل...","loadingOlderMessages": "جارٍ تحميل الرسائل الأقدم...",+ "loadOlderMessagesError": "تعذر تحميل الرسائل الأقدم. مرر لأعلى للمحاولة مرة أخرى.","noMessagesInChat": "لا توجد رسائل بعد. أرسل الرسالة الأولى للبدء!","downloadDocument": "تنزيل المستند","actions": {diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex bec5f0e08..8f55f3b85 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -88,6 +88,7 @@"unreadBadge_other": "{{count}} ungelesene Nachrichten","loadingMessages": "Nachrichten werden geladen...","loadingOlderMessages": "Ältere Nachrichten werden geladen...",+ "loadOlderMessagesError": "Ältere Nachrichten konnten nicht geladen werden. Zum erneuten Versuch nach oben scrollen.","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.jsonindex 56d9a206e..7dcf51e27 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -88,6 +88,7 @@"unreadBadge_other": "{{count}} unread messages","loadingMessages": "Loading messages...","loadingOlderMessages": "Loading older messages...",+ "loadOlderMessagesError": "Couldn't load older messages. Scroll up to retry.","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.jsonindex 69bfde018..87786163a 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -88,6 +88,7 @@"unreadBadge_other": "{{count}} mensajes sin leer","loadingMessages": "Cargando mensajes...","loadingOlderMessages": "Cargando mensajes anteriores...",+ "loadOlderMessagesError": "No se pudieron cargar los mensajes anteriores. Desplázate hacia arriba para reintentar.","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.jsonindex 83a46f46a..c60782751 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -88,6 +88,7 @@"unreadBadge_other": "{{count}} messages non lus","loadingMessages": "Chargement des messages...","loadingOlderMessages": "Chargement des messages plus anciens...",+ "loadOlderMessagesError": "Impossible de charger les messages plus anciens. Faites défiler vers le haut pour réessayer.","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.jsonindex 01d79ac4a..26691e631 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -90,6 +90,7 @@"unreadBadge_many": "{{count}} הודעות שלא נקראו","loadingMessages": "טוען הודעות...","loadingOlderMessages": "טוען הודעות ישנות יותר...",+ "loadOlderMessagesError": "טעינת ההודעות הישנות נכשלה. גלול למעלה כדי לנסות שוב.","noMessagesInChat": "אין הודעות עדיין. שלח את ההודעה הראשונה כדי להתחיל!","downloadDocument": "הורדת מסמך","actions": {diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 2d69a344b..4ac8fe404 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -88,6 +88,7 @@"unreadBadge_other": "{{count}} messaggi non letti","loadingMessages": "Caricamento messaggi...","loadingOlderMessages": "Caricamento messaggi precedenti...",+ "loadOlderMessagesError": "Impossibile caricare i messaggi precedenti. Scorri verso l’alto per riprovare.","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.jsonindex b3fb1736a..64a463e46 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -88,6 +88,7 @@"unreadBadge_other": "읽지 않은 메시지 {{count}}개","loadingMessages": "메시지 불러오는 중...","loadingOlderMessages": "이전 메시지 불러오는 중...",+ "loadOlderMessagesError": "이전 메시지를 불러오지 못했습니다. 위로 스크롤하여 다시 시도하세요.","noMessagesInChat": "아직 메시지가 없습니다. 첫 메시지를 보내 대화를 시작하세요!","downloadDocument": "문서 다운로드","actions": {diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 340a2a722..57f1af645 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -88,6 +88,7 @@"unreadBadge_other": "{{count}} mensagens não lidas","loadingMessages": "Carregando mensagens...","loadingOlderMessages": "Carregando mensagens anteriores...",+ "loadOlderMessagesError": "Não foi possível carregar mensagens anteriores. Role para cima para tentar novamente.","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.jsonindex f0f5c6d79..db562b317 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -88,6 +88,7 @@"unreadBadge_other": "{{count}} చదవని సందేశాలు","loadingMessages": "సందేశాలను లోడ్ చేస్తోంది...","loadingOlderMessages": "పాత సందేశాలను లోడ్ చేస్తోంది...",+ "loadOlderMessagesError": "పాత సందేశాలను లోడ్ చేయడం విఫలమైంది. మళ్లీ ప్రయత్నించడానికి పైకి స్క్రోల్ చేయండి.","noMessagesInChat": "ఇంకా సందేశాలు లేవు. ప్రారంభించడానికి మొదటి సందేశాన్ని పంపండి!","downloadDocument": "డాక్యుమెంట్ను డౌన్లోడ్ చేయి","actions": {diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex 256ff1dde..8ad3e441d 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -88,6 +88,7 @@"unreadBadge_other": "{{count}} okunmamış mesaj","loadingMessages": "Mesajlar yükleniyor...","loadingOlderMessages": "Daha eski mesajlar yükleniyor...",+ "loadOlderMessagesError": "Daha eski mesajlar yüklenemedi. Tekrar denemek için yukarı kaydırın.","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.jsonindex 02b56f9d8..220b4b9f0 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -88,6 +88,7 @@"unreadBadge_other": "{{count}} 条未读消息","loadingMessages": "正在加载消息...","loadingOlderMessages": "正在加载更早的消息...",+ "loadOlderMessagesError": "无法加载更早的消息。向上滚动重试。","noMessagesInChat": "暂无消息。发送第一条消息即可开始!","downloadDocument": "下载文档","actions": {diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 6869928aa..46af11181 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -88,6 +88,7 @@"unreadBadge_other": "{{count}} 條未讀訊息","loadingMessages": "正在載入訊息...","loadingOlderMessages": "正在載入較舊的訊息...",+ "loadOlderMessagesError": "無法載入較舊的訊息。向上捲動重試。","noMessagesInChat": "尚無訊息。傳送第一則訊息即可開始!","downloadDocument": "下載文件","actions": {diff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.cssindex 450aeff41..782561fd6 100644--- a/dashboard/src/pages/Chats.css+++ b/dashboard/src/pages/Chats.css@@ -431,6 +431,11 @@flex: 1;padding: 1.5rem;overflow-y: auto;+ /* Chrome/Firefox already adjust scrollTop on their own when content is prepended above the+ viewport (CSS scroll anchoring). The older-page handler applies its own correction for the+ same event, so leaving the browser's default on double-applies it. WebKit implements no+ scroll anchoring, so this is a no-op there and the manual correction is the only one that runs. */+ overflow-anchor: none;display: flex;flex-direction: column;gap: 0.75rem;diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsindex 805a201b2..3912ef435 100644--- a/dashboard/src/pages/Chats.test.ts+++ b/dashboard/src/pages/Chats.test.ts@@ -139,6 +139,20 @@ function holdOlderPage(): () => void {const pagedMessagesPath = (offset: number): string =>`/api/sessions/${SESSION.id}/messages?chatId=${encodeURIComponent(CHAT_2.id)}&limit=${PAGE_SIZE}&offset=${offset}`;+/**+ * Every fetch to Carol's paged route, at ANY offset. A count against one hardcoded offset (as+ * `pagedMessagesPath` builds) proves nothing about a request at some OTHER offset — a termination+ * rule that compares rows-held against a frozen total, instead of the short-page signal, would ask+ * for offset 120 here (PAGE_SIZE + PAGED_OLDEST.length), which a check against, say, `2 * PAGE_SIZE`+ * would silently miss.+ */+function countPagedMessagesFetches(): number {+ const prefix = `/api/sessions/${SESSION.id}/messages?chatId=${encodeURIComponent(CHAT_2.id)}&limit=${PAGE_SIZE}&offset=`;+ return fetchCalls.filter(c => c.method === 'GET' && c.path.startsWith(prefix)).length;+}++const flush = () => new Promise(resolve => setTimeout(resolve, 0));+/** The per-message media route the omitted marker sends the viewer to. */const mediaPathFor = (waMessageId: string): string =>`/api/sessions/${SESSION.id}/messages/${encodeURIComponent(CHAT.id)}/${encodeURIComponent(waMessageId)}/media`;@@ -644,11 +658,13 @@ test('scrolling to the top of a long thread pulls exactly one older page, then s// the engine-history merge would have inflated the latter past rows the DB never returned.await waitFor(() => assert.equal(countFetchCalls('GET', pagedMessagesPath(PAGE_SIZE)), 1));await within(thread).findByText('paged message 0');+ assert.equal(countPagedMessagesFetches(), 2);- // And it ends: the older page came back short, so a further scroll asks for nothing.+ // And it ends: the older page came back short (20 rows < PAGE_SIZE), so a further scroll asks+ // for nothing at all — not "nothing at 2 * PAGE_SIZE" (see countPagedMessagesFetches).fireEvent.scroll(thread);- await waitFor(() => assert.equal(countFetchCalls('GET', pagedMessagesPath(PAGE_SIZE)), 1));- assert.equal(countFetchCalls('GET', pagedMessagesPath(2 * PAGE_SIZE)), 0);+ await flush();+ assert.equal(countPagedMessagesFetches(), 2);});test('a delivery ack reaches a message held by an older page', async () => {@@ -758,3 +774,53 @@ test('a message arriving while an older page is in flight survives the page land// Still there, exactly once, after the page landed on top of it.await waitFor(() => assert.equal(within(thread).getAllByText('arrived mid-fetch').length, 1));});++test('a write during an in-flight older page survives leaving and returning to the chat', async () => {+ const { screen, fireEvent, within, waitFor } = rtl;+ resetFetchCalls();+ const { container } = renderChats();++ const thread = await openPagedChat(container);++ const releaseOlderPage = holdOlderPage();+ makeScrollable(thread, 0);+ fireEvent.scroll(thread);+ await waitFor(() => assert.ok(thread.querySelector('.messages-loading-older')));++ const socket = lastSocket();+ assert.ok(socket, 'expected the page to have opened a socket');+ socket.receive('message', {+ type: 'event',+ timestamp: new Date(1_700_002_100_000).toISOString(),+ payload: {+ event: 'message.received',+ sessionId: SESSION.id,+ data: {+ id: 'wamid.live.2',+ chatId: CHAT_2.id,+ from: CHAT_2.id,+ to: 'me',+ body: 'arrived while switching away',+ type: 'text',+ fromMe: false,+ timestamp: 1_700_001_600,+ },+ },+ });+ await within(thread).findByText('arrived while switching away');++ // Leave Carol's room WITHOUT waiting for the older page to land — this is the regression: the+ // in-flight fetch is not cancelled by leaving, so it still lands later and, unfixed, an unmount+ // that forgets the queued write above leaves nothing to replay it onto the result.+ fireEvent.click(await screen.findByText('Alice'));+ await within(container.querySelector('.room-header') as HTMLElement).findByText('Alice');++ releaseOlderPage();++ // Back to Carol. staleTime: Infinity means this reads the cache, not a fresh fetch — the same+ // landed-page data the departure left behind, now with the write replayed onto it.+ fireEvent.click(await screen.findByText('Carol'));+ const reopened = container.querySelector('.room-messages') as HTMLElement;+ await within(reopened).findByText('paged message 0');+ await waitFor(() => assert.equal(within(reopened).getAllByText('arrived while switching away').length, 1));+});diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex e612d34a5..a52512346 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -788,8 +788,9 @@ export const sessionApi = {body: JSON.stringify({ chatId }),}),// `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.+ // these with engine history, so paging by the merged length would skip DB rows. `total` is not+ // read to decide whether an older page exists — a page short of `limit` is; a chat with live+ // traffic keeps growing `total` after the fact, so comparing rows-held against it stops early.getChatMessages: (id: string, chatId: string, limit = 100, offset = 0) =>request<{ messages: ChatMessage[]; total: number }>(`/sessions/${id}/messages?chatId=${encodeURIComponent(chatId)}&limit=${limit}&offset=${offset}`,diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.tsindex 97335e4f9..cf451c900 100644--- a/dashboard/src/utils/chatMessages.ts+++ b/dashboard/src/utils/chatMessages.ts@@ -206,13 +206,13 @@ function mergeMessageMetadata(* waMessageId=WA id) and a live WS message (id=WA id) for the same WhatsApp message must dedupe,* not double-add. On replace, the delivery status only advances (a replayed lower `sent` echo can't* downgrade a delivered/read row) and metadata is merged per field (a payload-less echo can't erase- * the existing media/quote — see mergeMessageMetadata). The result is run through capMediaPayloads- * so a long session of incoming media can't grow the cached slice's base64 heap without bound.- * Returns a new array — does not mutate the input.+ * the existing media/quote — see mergeMessageMetadata). Returns a new array — does not mutate the+ * input. Order-agnostic: unlike {@link mergeOrAppend}, this does not cap media payloads, which+ * requires knowing which end of the list is oldest.*/-export function mergeOrAppend(list: ChatMessageView[], incoming: ChatMessageView): ChatMessageView[] {+export function mergeOrAppendUncapped(list: ChatMessageView[], incoming: ChatMessageView): ChatMessageView[] {const idx = list.findIndex(m => msgKey(m) === msgKey(incoming));- if (idx === -1) return capMediaPayloads([...list, incoming]);+ if (idx === -1) return [...list, incoming];const existing = list[idx];const next = list.slice();next[idx] = {@@ -222,7 +222,16 @@ export function mergeOrAppend(list: ChatMessageView[], incoming: ChatMessageViewstatus: mergeDeliveryStatus(existing.status, incoming.status) ?? incoming.status,metadata: mergeMessageMetadata(existing.metadata, incoming.metadata),};- return capMediaPayloads(next);+ return next;+}++/**+ * {@link mergeOrAppendUncapped}, then capMediaPayloads so a long session of incoming media can't+ * grow the list's base64 heap without bound. Requires an ASCENDING (oldest-first) `list` — the cap+ * strips from the front, so passing a `createdAt DESC` page would strip the newest payloads first.+ */+export function mergeOrAppend(list: ChatMessageView[], incoming: ChatMessageView): ChatMessageView[] {+ return capMediaPayloads(mergeOrAppendUncapped(list, incoming));}/**diff --git a/dashboard/src/utils/messagePages.test.ts b/dashboard/src/utils/messagePages.test.tsindex 0a014e71c..6ad347d73 100644--- a/dashboard/src/utils/messagePages.test.ts+++ b/dashboard/src/utils/messagePages.test.ts@@ -66,6 +66,24 @@ test('live messages move the cursor without ending the paging', () => {assert.equal(nextMessagePageParam(pages, PAGE_SIZE), 105);});+test('a failed send does not shift the cursor past a real row', () => {+ // ChatComposer's tempId is `temp_${Date.now()}`; a failed one stays in page.db with+ // status: 'failed' forever (nothing removes it). Counting it as a fetched row offsets every+ // later page by one and permanently strands whichever real row that offset skips.+ const pages = [page([...rows(PAGE_SIZE, 'db-'), msg('temp_1700000000000', { status: 'failed' })], PAGE_SIZE)];++ assert.equal(dbRowsFetched(pages), PAGE_SIZE);+ assert.equal(nextMessagePageParam(pages, PAGE_SIZE), PAGE_SIZE);+});++test('a genuine DB row with no waMessageId still counts', () => {+ // The exclusion is matched on the id PREFIX, not on a missing waMessageId — that field is+ // nullable on a real persisted row too, so using its absence as the signal would double-count.+ const pages = [page([msg('db-1', { waMessageId: undefined })])];++ assert.equal(dbRowsFetched(pages), 1);+});+test('a live message lands on the newest page', () => {const pages = [page([msg('new')]), page([msg('old')])];diff --git a/dashboard/src/utils/messagePages.ts b/dashboard/src/utils/messagePages.tsindex e89614807..1d4932311 100644--- a/dashboard/src/utils/messagePages.ts+++ b/dashboard/src/utils/messagePages.ts@@ -1,4 +1,4 @@-import { mergeOrAppend, type ChatMessageView } from './chatMessages.ts';+import { mergeOrAppendUncapped, type ChatMessageView } from './chatMessages.ts';/*** One fetched slice of a chat's history. `db` and `history` stay separate because the page cursor is@@ -15,9 +15,18 @@ export interface MessagePage {fetched: number;}+/**+ * Optimistic-send placeholders (ChatComposer's `temp_${Date.now()}` id) never reached the DB. One+ * that failed stays in `page.db` with `status: 'failed'` and nothing ever removes it, so counting+ * it as a fetched row would offset every later page by one and strand a real row unreachable.+ * Matched on the id prefix specifically — not on a missing `waMessageId`, which is nullable on a+ * genuine DB row too.+ */+const isOptimisticPlaceholder = (m: ChatMessageView): boolean => m.id.startsWith('temp_');+/** 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);+ return pages.reduce((count, page) => count + page.db.filter(m => !isOptimisticPlaceholder(m)).length, 0);}/**@@ -39,9 +48,13 @@ 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.+ * Which page receives it matters: a plain append (finding no match) would add a copy to every page+ * run this way, so the message is merged into the page that already holds it, landing on the newest+ * page only when no page does. Uses the uncapped merge deliberately: `page.db` is server order+ * (`createdAt DESC`, newest first), and the payload cap strips from the front of an ASCENDING list —+ * on this order it would strip the newest payloads first. The real cap already runs once, correctly+ * ordered, on the flattened thread `select` produces; capping each page too would be redundant even+ * pointed the right way, since one page rarely nears MEDIA_PAYLOAD_CACHE_LIMIT on its own.*/export function upsertIntoPages(pages: MessagePage[], incoming: ChatMessageView, dropId?: string): MessagePage[] {const trimmed = dropId@@ -53,5 +66,5 @@ export function upsertIntoPages(pages: MessagePage[], incoming: ChatMessageView,: 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));+ return trimmed.map((page, i) => (i === index ? { ...page, db: mergeOrAppendUncapped(page.db, incoming) } : page));}