Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): read the message cache as pages in the realtime handlers

JuanGalzeranoc3a495c9274f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9ff6fcbe7..7fa6bd9ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,10 +13,12 @@ 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.
+- The dashboard chat room loads older history as you scroll up. It used to show one fixed window —
+ the newest 100 persisted rows plus up to 100 rows of engine history merged in, so roughly 200
+ messages — with no way to reach anything older. 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/hooks/useChatMessages.ts b/dashboard/src/hooks/useChatMessages.ts
index 588421561..93f99c2ac 100644
--- a/dashboard/src/hooks/useChatMessages.ts
+++ b/dashboard/src/hooks/useChatMessages.ts
@@ -5,15 +5,16 @@ import {
type UseInfiniteQueryResult,
} from '@tanstack/react-query';
import type { QueryClient } from '@tanstack/react-query';
+import { useEffect } from 'react';
import {
mergeChatMessages,
mapEngineHistoryMessage,
updateMessageById,
removeMessageById,
type ChatMessageView,
-} from '../utils/chatMessages.ts';
-import { upsertIntoPages, nextMessagePageParam, type MessagePage } from '../utils/messagePages.ts';
-import { sessionApi } from '../services/api.ts';
+} from '../utils/chatMessages';
+import { upsertIntoPages, nextMessagePageParam, type MessagePage } from '../utils/messagePages';
+import { sessionApi } from '../services/api';
export type MessagesQueryKey = readonly ['messages', string, string];
@@ -26,6 +27,17 @@ export const MESSAGE_PAGE_SIZE = 100;
export type MessagesData = InfiniteData<MessagePage>;
+/**
+ * The one flat chronological view of a paged cache. A single page is newest-first and partial, so
+ * neither a message's position nor its absence can be read from one.
+ */
+export function flattenMessagePages(data: MessagesData): ChatMessageView[] {
+ return mergeChatMessages(
+ data.pages.flatMap(page => page.db),
+ data.pages.flatMap(page => page.history),
+ );
+}
+
/**
* Fetch a chat's messages a page at a time, newest page first, cached at staleTime: Infinity;
* realtime updates flow through useChatMessagesActions, not refetches.
@@ -33,12 +45,17 @@ export type MessagesData = InfiniteData<MessagePage>;
* 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.
+ *
+ * Base64 media payloads are bounded by capMediaPayloads, which now runs inside `select` and so
+ * bounds the RENDERED set rather than the cache: pages accumulate raw, and the newest
+ * MEDIA_PAYLOAD_CACHE_LIMIT payloads are the ones that stay renderable.
*/
export function useChatMessages(
sessionId: string,
chatId: string | null,
): UseInfiniteQueryResult<ChatMessageView[], Error> {
- return useInfiniteQuery<MessagePage, Error, ChatMessageView[], MessagesQueryKey, number>({
+ const queryClient = useQueryClient();
+ const query = useInfiniteQuery<MessagePage, Error, ChatMessageView[], MessagesQueryKey, number>({
queryKey: messagesQueryKey(sessionId, chatId ?? ''),
initialPageParam: 0,
queryFn: async ({ pageParam }) => {
@@ -51,56 +68,116 @@ export function useChatMessages(
// 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 db = dbRes.status === 'fulfilled' ? dbRes.value : { messages: [] };
const history = historyRes.status === 'fulfilled' ? historyRes.value.map(mapEngineHistoryMessage) : [];
- return { db: db.messages, history, total: db.total };
+ return { db: db.messages, history, fetched: db.messages.length };
},
- getNextPageParam: (_lastPage, allPages) => nextMessagePageParam(allPages),
+ getNextPageParam: (_lastPage, allPages) => nextMessagePageParam(allPages, MESSAGE_PAGE_SIZE),
// 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),
- ),
+ select: flattenMessagePages,
enabled: Boolean(sessionId && chatId),
staleTime: Infinity,
gcTime: 5 * 60 * 1000,
});
+
+ // A page in flight carries a snapshot of `data.pages` taken when it started (TanStack's
+ // 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]);
+ useEffect(() => {
+ if (isFetching) return;
+ replayWritesLostToFetch(queryClient, messagesQueryKey(sessionId, chatId ?? ''));
+ }, [queryClient, isFetching, sessionId, chatId]);
+
+ return query;
+}
+
+interface PendingWrite {
+ apply: (data: MessagesData) => MessagesData;
+ /** The cache value this write produced — see replayWritesLostToFetch. */
+ wrote: MessagesData | undefined;
}
+// Module scope because the helpers below are plain functions with no component to hang state on.
+const writesLostToFetch = new Map<string, PendingWrite[]>();
+
+const pendingKey = (key: MessagesQueryKey): string => JSON.stringify(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.
+ * Apply one change to a chat's paged cache, recording it for replay when a page is in flight.
+ *
+ * Never seeds a slice: an entry created here would be "fresh" under staleTime: Infinity, so opening
+ * the chat would skip the queryFn and show this write alone.
+ *
+ * `apply` must be idempotent: a replay can re-run it against a cache that already reflects it.
*/
-function mapCachedMessages(
+function writeMessagesCache(
queryClient: QueryClient,
key: MessagesQueryKey,
- transform: (list: ChatMessageView[]) => ChatMessageView[],
+ apply: (data: MessagesData) => MessagesData,
): void {
+ const state = queryClient.getQueryState<MessagesData>(key);
+ if (state?.data === undefined) return;
+ queryClient.setQueryData<MessagesData>(key, old => (old === undefined ? undefined : apply(old)));
+ if (state.fetchStatus !== 'fetching') return;
+ const id = pendingKey(key);
+ const wrote = queryClient.getQueryData<MessagesData>(key);
+ writesLostToFetch.set(id, [...(writesLostToFetch.get(id) ?? []), { apply, wrote }]);
+}
+
+/**
+ * Re-apply, in order, the writes a landed page overwrote.
+ *
+ * Only if one actually did. A fetch that FAILED leaves the cache exactly as the last queued write
+ * left it, so nothing was lost and replaying would apply the whole queue twice. Identity answers
+ * that in one comparison — a landed page always produces a new value — and it is a per-QUEUE
+ * question, not a per-entry one: either a fetch replaced the data, in which case every queued
+ * write went with it, or it did not, in which case none did.
+ */
+export function replayWritesLostToFetch(queryClient: QueryClient, key: MessagesQueryKey): void {
+ const id = pendingKey(key);
+ const queue = writesLostToFetch.get(id);
+ if (queue === undefined || queue.length === 0) return;
+ writesLostToFetch.delete(id);
+ if (queue[queue.length - 1].wrote === queryClient.getQueryData<MessagesData>(key)) return;
queryClient.setQueryData<MessagesData>(key, old =>
- old === undefined
- ? undefined
- : {
- ...old,
- pages: old.pages.map(page => ({
- ...page,
- db: transform(page.db),
- history: transform(page.history),
- })),
- },
+ old === undefined ? undefined : queue.reduce((data, write) => write.apply(data), old),
);
}
+/** 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));
+}
+
/**
- * 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.
+ * 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.
+ *
+ * The transform sees one page at a time, so it must not depend on the thread's order or
+ * completeness — `flattenMessagePages` answers those questions.
*/
export function updateCachedMessages(
queryClient: QueryClient,
key: MessagesQueryKey,
transform: (list: ChatMessageView[]) => ChatMessageView[],
): void {
- mapCachedMessages(queryClient, key, transform);
+ writeMessagesCache(queryClient, key, data => ({
+ ...data,
+ pages: data.pages.map(page => ({ ...page, db: transform(page.db), history: transform(page.history) })),
+ }));
}
/**
@@ -116,13 +193,32 @@ export function upsertCachedMessage(
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) },
+ writeMessagesCache(queryClient, key, data =>
+ data.pages.length === 0 ? data : { ...data, pages: upsertIntoPages(data.pages, incoming, options.dropId) },
);
}
+/**
+ * The cached chats under one session that hold a matching message, as [key, flat thread] pairs.
+ *
+ * `matches` is applied to the raw pages first so only a thread that actually holds the message pays
+ * for the merge — a realtime event concerns one chat, and flattening every open one per event would
+ * sort and cap them all to throw the result away.
+ */
+export function cachedSessionThreads(
+ queryClient: QueryClient,
+ sessionId: string,
+ matches: (message: ChatMessageView) => boolean,
+): Array<[MessagesQueryKey, ChatMessageView[]]> {
+ const threads: Array<[MessagesQueryKey, ChatMessageView[]]> = [];
+ for (const [key, data] of queryClient.getQueriesData<MessagesData>({ queryKey: ['messages', sessionId] })) {
+ if (data === undefined) continue;
+ const holds = data.pages.some(page => page.db.some(matches) || page.history.some(matches));
+ if (holds) threads.push([key as MessagesQueryKey, flattenMessagePages(data)]);
+ }
+ return threads;
+}
+
/**
* Mutation helpers that write directly to the React Query cache. Use these
* from the WebSocket subscriber, the optimistic-send flow, and ACK handlers
@@ -133,16 +229,13 @@ export function useChatMessagesActions() {
return {
appendMessage(sessionId: string, chatId: string, msg: ChatMessageView) {
- // 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>) {
- mapCachedMessages(qc, messagesQueryKey(sessionId, chatId), list => updateMessageById(list, id, patch));
+ updateCachedMessages(qc, messagesQueryKey(sessionId, chatId), list => updateMessageById(list, id, patch));
},
removeMessage(sessionId: string, chatId: string, id: string) {
- mapCachedMessages(qc, messagesQueryKey(sessionId, chatId), list => removeMessageById(list, id));
+ updateCachedMessages(qc, messagesQueryKey(sessionId, chatId), list => removeMessageById(list, id));
},
};
}
diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.ts
index 2a05455da..2bb2aecdf 100644
--- a/dashboard/src/hooks/useChatScrollPosition.ts
+++ b/dashboard/src/hooks/useChatScrollPosition.ts
@@ -72,12 +72,13 @@ export function isNearBottom(scrollTop: number, scrollHeight: number, clientHeig
export function useChatScrollPosition(
activeChatId: string | null,
isLoaded: boolean,
+ isFetchingOlderMessages: boolean,
): {
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;
+ /** Call when an older page is requested; the reading position is held once it lands. */
+ onOlderMessagesRequested: () => void;
} {
const containerRef = useRef<HTMLDivElement | null>(null);
const scrollMap = useRef<Map<string, number>>(new Map());
@@ -90,6 +91,10 @@ export function useChatScrollPosition(
// Marks our own writes so the scroll listener can skip them (a genuine user scroll both updates
// the pin state / position map AND cancels pendingRestore; our writes must do neither).
const programmaticWriteRef = useRef<boolean>(false);
+ // See the layout effect below.
+ const prevScrollHeightRef = useRef<number>(0);
+ const awaitingOlderPageRef = useRef<boolean>(false);
+ const wasFetchingOlderRef = useRef<boolean>(false);
const writeScrollTop = useCallback((el: HTMLDivElement, top: number) => {
const before = el.scrollTop;
@@ -138,6 +143,9 @@ export function useChatScrollPosition(
const el = containerRef.current;
// A new restore decision supersedes any pending one (it belongs to a different chat/visit).
pendingRestoreRef.current = null;
+ // Same for a page still in flight: its delta belongs to the thread being left. This effect is
+ // declared before the height tracker, so the flag is gone before the tracker could act on it.
+ if (next !== prevChatIdRef.current) awaitingOlderPageRef.current = false;
const decision = decideRestoreTarget(next, isLoaded, next !== null ? scrollMap.current.get(next) : undefined);
@@ -157,6 +165,39 @@ export function useChatScrollPosition(
prevChatIdRef.current = next;
}, [activeChatId, isLoaded, pinToBottom, writeScrollTop]);
+ // Older messages are prepended ABOVE the viewport, so the thread grows upward and what the user
+ // was reading is pushed down by however much taller it just got. Left alone the view jumps
+ // backwards at the exact moment they asked for more.
+ //
+ // The height is read when the page is REQUESTED and the delta applied on the commit where the
+ // in-flight flag falls — not on the first commit whose height changed, because the older-page
+ // spinner is an in-flow child of this same container (ChatThread) and its own ~46px arrives one
+ // commit earlier. Only `scrollHeight` is held; `scrollTop` is read live at apply time, so a
+ // deliberate reposition made during the fetch survives. The pin/restore machinery above is not
+ // reused: it writes an ABSOLUTE target, which is unknowable here.
+ useLayoutEffect(() => {
+ const el = containerRef.current;
+ const wasFetching = wasFetchingOlderRef.current;
+ wasFetchingOlderRef.current = isFetchingOlderMessages;
+ // The FALLING edge, not merely "not fetching": the request is made in a scroll handler and the
+ // query only reports itself in flight a turn later, so any commit in between — a live message,
+ // a media decode, another query resolving — would otherwise consume the pending correction.
+ if (!el || isFetchingOlderMessages || !wasFetching || !awaitingOlderPageRef.current) return;
+ awaitingOlderPageRef.current = false;
+ // A live message landing mid-fetch is inside this delta too, and it grew the thread at the
+ // BOTTOM where no correction is wanted — one bubble of overshoot in that race, against a whole
+ // page of it if the prepend went uncorrected.
+ const grew = el.scrollHeight - prevScrollHeightRef.current;
+ if (grew > 0) writeScrollTop(el, el.scrollTop + grew);
+ });
+
+ const onOlderMessagesRequested = useCallback(() => {
+ const el = containerRef.current;
+ if (!el) return;
+ prevScrollHeightRef.current = el.scrollHeight;
+ awaitingOlderPageRef.current = true;
+ }, []);
+
const onMessageAppended = useCallback(
(direction: ScrollDirection) => {
const el = containerRef.current;
@@ -195,24 +236,5 @@ export function useChatScrollPosition(
});
}, [pinToBottom, writeScrollTop]);
- // 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 };
+ return { containerRef, onMessageAppended, onMediaLoad, onOlderMessagesRequested };
}
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index 68426d46e..805a201b2 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -17,6 +17,9 @@ import { createElement } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { Session, Chat, ChatMessage } from '../services/api';
import type { installJsdomGlobals as installJsdomGlobalsFn } from '../test-helpers/jsdom.ts';
+// socket.io-client resolves to a double under this runner (see vite-shim-hooks.mjs), which is what
+// lets a test deliver a server frame to the page's realtime handlers.
+import { lastSocket, resetSocketDouble } from '../test-helpers/socket-io-double.ts';
// ── Fixtures + fetch stub ────────────────────────────────────────────────────
@@ -94,6 +97,48 @@ const OMITTED_MEDIA_MESSAGE_2: ChatMessage = {
metadata: { media: { mimetype: 'image/jpeg', filename: 'photo-2.jpg', omitted: true, sizeBytes: 9_000_000 } },
};
+// Carol's thread is long enough to page: a full first page, then a short older one that ends it.
+// Each row's body carries its index so a test can name the exact bubble a given page brought in.
+const PAGE_SIZE = 100;
+
+const pagedRow = (index: number, extra: Partial<ChatMessage> = {}): ChatMessage => ({
+ id: `paged-${index}`,
+ waMessageId: `wamid.paged.${index}`,
+ chatId: CHAT_2.id,
+ from: CHAT_2.id,
+ to: 'me',
+ body: `paged message ${index}`,
+ type: 'text',
+ direction: 'incoming',
+ status: 'delivered',
+ timestamp: 1_700_001_000 + index,
+ createdAt: new Date((1_700_001_000 + index) * 1000).toISOString(),
+ ...extra,
+});
+
+// Newest first, the order the gateway returns (createdAt DESC): 119 down to 20 on the first page,
+// 19 down to 0 on the second. The second is short, which is what ends the paging. Row 0 is ours and
+// unacked, so the ack test has a delivery tick to watch on a row only the oldest page holds.
+const PAGED_NEWEST = Array.from({ length: PAGE_SIZE }, (_, i) => pagedRow(119 - i));
+const PAGED_OLDEST = Array.from({ length: 20 }, (_, i) =>
+ i === 19 ? pagedRow(0, { direction: 'outgoing', from: 'me', to: CHAT_2.id, status: 'sent' }) : pagedRow(19 - i),
+);
+
+// Hold the older page open so the spinner commit and the landing commit stay distinct.
+let olderPageGate: Promise<void> | null = null;
+
+function holdOlderPage(): () => void {
+ let release!: () => void;
+ olderPageGate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ return release;
+}
+
+/** The messages route for one page of Carol's thread, as the api client spells it. */
+const pagedMessagesPath = (offset: number): string =>
+ `/api/sessions/${SESSION.id}/messages?chatId=${encodeURIComponent(CHAT_2.id)}&limit=${PAGE_SIZE}&offset=${offset}`;
+
/** 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`;
@@ -186,6 +231,14 @@ function installFetchStub(): void {
return Promise.resolve(jsonResponse([CONTACT]));
}
if (method === 'GET' && path.startsWith(`/api/sessions/${SESSION.id}/messages?`)) {
+ const query = new URLSearchParams(path.slice(path.indexOf('?') + 1));
+ if (query.get('chatId') === CHAT_2.id) {
+ const isFirstPage = Number(query.get('offset')) === 0;
+ const messages = isFirstPage ? PAGED_NEWEST : PAGED_OLDEST;
+ const answer = () => jsonResponse({ messages, total: PAGED_NEWEST.length + PAGED_OLDEST.length });
+ const gate = isFirstPage ? null : olderPageGate;
+ return gate ? gate.then(answer) : Promise.resolve(answer());
+ }
return Promise.resolve(
jsonResponse({ messages: [DB_MESSAGE, OMITTED_MEDIA_MESSAGE, OMITTED_MEDIA_MESSAGE_2], total: 3 }),
);
@@ -236,6 +289,9 @@ before(async () => {
// RoleProvider initializes from localStorage; 'admin' makes canWrite true so the composer
// controls render enabled.
window.localStorage.setItem('openwa_user_role', 'admin');
+ // useWebSocket.connect() bails without this, so no socket would exist to receive a frame. It
+ // dials nothing: the client is the double above.
+ window.sessionStorage.setItem('openwa_api_key', 'test-key');
// The real i18n instance, and then its readiness promise: catalogues are fetched rather than
// bundled, so importing the module only STARTS the load. Every `getByText` below is English copy
// out of en.json, which renders as a raw key until it lands. Awaiting is what makes that
@@ -251,10 +307,12 @@ before(async () => {
afterEach(() => {
rtl.cleanup();
+ resetSocketDouble();
queryClient?.clear();
queryClient = undefined;
- // A gate left held would stall the next test's media fetch forever.
+ // A gate left held would stall the next test's fetch forever.
mediaGates.clear();
+ olderPageGate = null;
});
function renderChats(): { container: HTMLElement } {
@@ -526,3 +584,177 @@ test('two media downloads in flight do not clobber each other', async () => {
"B's download was still open — A settling must not re-enable it",
);
});
+
+// ── Paging, and realtime over a paged cache ──────────────────────────────────
+
+/** Modelled heights, so a commit that changes the thread's contents changes its scrollHeight. */
+const BUBBLE_PX = 30;
+const OLDER_SPINNER_PX = 46;
+
+/**
+ * Give the thread container a scrollable geometry. jsdom lays nothing out, so every offset reads 0
+ * and the page would never see a thread it can scroll.
+ *
+ * `scrollHeight` is a getter over the live DOM rather than a constant: the older-page spinner is an
+ * in-flow child of this container, so it grows the thread on its own commit, one commit BEFORE the
+ * page lands. A constant cannot tell those two commits apart, and the scroll-restore test below
+ * turns entirely on the difference.
+ */
+function makeScrollable(thread: HTMLElement, scrollTop: number): void {
+ Object.defineProperty(thread, 'clientHeight', { value: 600, configurable: true });
+ Object.defineProperty(thread, 'scrollHeight', {
+ configurable: true,
+ get: () =>
+ thread.querySelectorAll('.message-bubble').length * BUBBLE_PX +
+ (thread.querySelector('.messages-loading-older') ? OLDER_SPINNER_PX : 0),
+ });
+ let top = scrollTop;
+ Object.defineProperty(thread, 'scrollTop', {
+ configurable: true,
+ get: () => top,
+ set: (value: number) => {
+ top = value;
+ },
+ });
+}
+
+/** Open Carol's thread and return its scroll container, with the first page rendered. */
+async function openPagedChat(container: HTMLElement): Promise<HTMLElement> {
+ const { screen, fireEvent, within } = rtl;
+ await screen.findByText('Main (15551234567)');
+ fireEvent.click(await screen.findByText('Carol'));
+ const thread = container.querySelector('.room-messages') as HTMLElement;
+ await within(thread).findByText('paged message 119');
+ return thread;
+}
+
+test('scrolling to the top of a long thread pulls exactly one older page, then stops', async () => {
+ const { fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ const { container } = renderChats();
+
+ const thread = await openPagedChat(container);
+ assert.equal(within(thread).queryByText('paged message 0'), null);
+ assert.equal(countFetchCalls('GET', pagedMessagesPath(0)), 1);
+
+ makeScrollable(thread, 0);
+ fireEvent.scroll(thread);
+
+ // Asked for at the number of DB rows already held, not at the length of the rendered thread —
+ // 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');
+
+ // And it ends: the older page came back short, so a further scroll asks for nothing.
+ fireEvent.scroll(thread);
+ await waitFor(() => assert.equal(countFetchCalls('GET', pagedMessagesPath(PAGE_SIZE)), 1));
+ assert.equal(countFetchCalls('GET', pagedMessagesPath(2 * PAGE_SIZE)), 0);
+});
+
+test('a delivery ack reaches a message held by an older page', async () => {
+ const { fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ const { container } = renderChats();
+
+ const thread = await openPagedChat(container);
+ makeScrollable(thread, 0);
+ fireEvent.scroll(thread);
+ await within(thread).findByText('paged message 0');
+
+ const statusIcon = (): Element | null =>
+ within(thread).getByText('paged message 0').closest('.message-bubble')?.querySelector('.message-status-icon') ??
+ null;
+ assert.ok(statusIcon()?.classList.contains('sent'), 'expected the row to start unacked');
+
+ // The regression this locks out: the realtime handlers used to read this cache as a flat array.
+ // Against the paged shape the ack threw `list.findIndex is not a function` inside a listener with
+ // no try/catch, so delivery ticks, reactions, revokes and edits stopped working in any open chat
+ // with nothing surfaced to the user. The acked row is on the OLDEST page, so a handler that only
+ // walked page 0 would miss it too.
+ 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_000_000).toISOString(),
+ payload: {
+ event: 'message.ack',
+ sessionId: SESSION.id,
+ data: { id: 'paged-0', messageId: 'wamid.paged.0', status: 'read', ack: 3 },
+ },
+ });
+
+ await waitFor(() => assert.ok(statusIcon()?.classList.contains('read'), 'expected the read tick on the acked row'));
+});
+
+test('the reading position is held across the commit that lands an older page', async () => {
+ const { fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ const { container } = renderChats();
+
+ const thread = await openPagedChat(container);
+ await waitFor(() => assert.equal(thread.querySelectorAll('.message-bubble').length, PAGE_SIZE));
+
+ const releaseOlderPage = holdOlderPage();
+ makeScrollable(thread, 0);
+ const before = thread.scrollHeight;
+ fireEvent.scroll(thread);
+
+ await waitFor(() => assert.ok(thread.querySelector('.messages-loading-older')));
+ assert.equal(thread.scrollHeight, before + OLDER_SPINNER_PX);
+
+ releaseOlderPage();
+ await within(thread).findByText('paged message 0');
+ await waitFor(() => assert.equal(thread.querySelector('.messages-loading-older'), null));
+
+ // The thread grew upward by the new bubbles, so the row the user was reading has to move down by
+ // exactly that much. The regression this locks out: measuring the growth on the first commit that
+ // changed scrollHeight caught the older-page SPINNER entering the flow, one commit early, and
+ // spent the correction on its ~46px — leaving the real prepend uncorrected and the view thrown a
+ // full page backwards.
+ assert.equal(thread.scrollHeight - before, PAGED_OLDEST.length * BUBBLE_PX);
+ assert.equal(thread.scrollTop, PAGED_OLDEST.length * BUBBLE_PX);
+});
+
+test('a message arriving while an older page is in flight survives the page landing', async () => {
+ const { 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')));
+
+ // The regression this locks out: a page in flight carries a snapshot of `data.pages` taken when
+ // it started, so its result overwrites anything written meanwhile — and at staleTime: Infinity
+ // no refetch brings it back. Without the replay the bubble below is gone for good.
+ 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_000_000).toISOString(),
+ payload: {
+ event: 'message.received',
+ sessionId: SESSION.id,
+ data: {
+ id: 'wamid.live.1',
+ chatId: CHAT_2.id,
+ from: CHAT_2.id,
+ to: 'me',
+ body: 'arrived mid-fetch',
+ type: 'text',
+ fromMe: false,
+ timestamp: 1_700_001_500,
+ },
+ },
+ });
+ await within(thread).findByText('arrived mid-fetch');
+
+ releaseOlderPage();
+ await within(thread).findByText('paged message 0');
+
+ // Still there, exactly once, after the page landed on top of it.
+ await waitFor(() => assert.equal(within(thread).getAllByText('arrived mid-fetch').length, 1));
+});
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index f78602354..8cccd9329 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -25,6 +25,8 @@ import {
mergeDeliveryStatus,
mergeReactionSnapshot,
findRevokedIndex,
+ patchMatchingMessage,
+ byMessageId,
getMediaSrc,
type ChatMessageView,
type MessageMedia,
@@ -39,6 +41,7 @@ import {
useChatMessagesActions,
messagesQueryKey,
updateCachedMessages,
+ cachedSessionThreads,
} from '../hooks/useChatMessages';
import { useChannelMessages } from '../hooks/useChannelMessages';
import { useContactStatuses } from '../hooks/useContactStatuses';
@@ -232,27 +235,13 @@ 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);
+ onOlderMessagesRequested,
+ } = useChatScrollPosition(activeChat?.id ?? null, messages.length > 0, loadingOlderMessages);
+
const handleLoadOlderMessages = useCallback(() => {
- restoreOlderScrollRef.current = onOlderMessagesPrepended();
+ onOlderMessagesRequested();
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]);
+ }, [fetchNextPage, onOlderMessagesRequested]);
// 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
@@ -423,22 +412,17 @@ export function Chats() {
(event: { sessionId: string; messageId: string; status: ChatMessageView['status'] }) => {
if (event.sessionId !== selectedSessionId) return;
- // Acks can arrive for any cached chat under this session. Walk every cache entry under
- // ['messages', event.sessionId, *] and apply the forward-only delivery merge in place.
- const caches = queryClient.getQueriesData<ChatMessageView[]>({
- queryKey: ['messages', event.sessionId],
- });
- for (const [key, list] of caches) {
- if (!list) continue;
- const idx = list.findIndex(m => m.id === event.messageId || m.waMessageId === event.messageId);
- if (idx === -1) continue;
- const target = list[idx];
+ // Acks can arrive for any cached chat under this session, so every thread is checked.
+ for (const [key, thread] of cachedSessionThreads(queryClient, event.sessionId, byMessageId(event.messageId))) {
+ const target = thread.find(byMessageId(event.messageId));
+ if (!target) continue;
// Backend now sends the neutral delivery status directly (no engine-specific ack codes).
// Merge forward-only so an out-of-order/replayed lower ack can't downgrade the tick.
const nextStatus = mergeDeliveryStatus(target.status, event.status) ?? target.status;
- const next = list.slice();
- next[idx] = { ...target, status: nextStatus };
- queryClient.setQueryData(key, next);
+ if (nextStatus === target.status) continue;
+ updateCachedMessages(queryClient, key, list =>
+ patchMatchingMessage(list, event.messageId, m => ({ ...m, status: nextStatus })),
+ );
}
},
[selectedSessionId, queryClient],
@@ -454,23 +438,16 @@ export function Chats() {
//
// The absent-vs-empty distinction on `reactions` is mergeReactionSnapshot's job; it is a named
// function so the behaviour is covered by a test, because nothing here is.
- const caches = queryClient.getQueriesData<ChatMessageView[]>({
- queryKey: ['messages', event.sessionId],
- });
- for (const [key, list] of caches) {
- if (!list) continue;
- const idx = list.findIndex(m => m.id === event.messageId || m.waMessageId === event.messageId);
- if (idx === -1) continue;
- const target = list[idx];
- const next = list.slice();
- next[idx] = {
- ...target,
- metadata: {
- ...(target.metadata || {}),
- reactions: mergeReactionSnapshot(target.metadata?.reactions, event.reactions),
- },
- };
- queryClient.setQueryData(key, next);
+ for (const [key] of cachedSessionThreads(queryClient, event.sessionId, byMessageId(event.messageId))) {
+ updateCachedMessages(queryClient, key, list =>
+ patchMatchingMessage(list, event.messageId, m => ({
+ ...m,
+ metadata: {
+ ...(m.metadata || {}),
+ reactions: mergeReactionSnapshot(m.metadata?.reactions, event.reactions),
+ },
+ })),
+ );
}
},
[selectedSessionId, queryClient],
@@ -483,17 +460,15 @@ export function Chats() {
// Walk every cached chat under this session, find the deleted message and zero it — the
// backend emits an empty body; the localized "deleted" label is rendered below. Matching is
// in findRevokedIndex: the event carries two candidate ids and wwebjs's `id` alone can miss.
- const caches = queryClient.getQueriesData<ChatMessageView[]>({
- queryKey: ['messages', event.sessionId],
- });
- for (const [key, list] of caches) {
- if (!list) continue;
- const idx = findRevokedIndex(list, event);
- if (idx === -1) continue;
- const target = list[idx];
- const next = list.slice();
- next[idx] = { ...target, body: '', type: asMessageType(event.type) };
- queryClient.setQueryData(key, next);
+ const revoked = (m: ChatMessageView): boolean => findRevokedIndex([m], event) !== -1;
+ for (const [key] of cachedSessionThreads(queryClient, event.sessionId, revoked)) {
+ updateCachedMessages(queryClient, key, list => {
+ const idx = findRevokedIndex(list, event);
+ if (idx === -1) return list;
+ const next = list.slice();
+ next[idx] = { ...next[idx], body: '', type: asMessageType(event.type) };
+ return next;
+ });
}
},
[selectedSessionId, queryClient],
@@ -503,23 +478,19 @@ export function Chats() {
(event: { sessionId: string; messageId: string; chatId: string; body: string }) => {
if (event.sessionId !== selectedSessionId) return;
- const caches = queryClient.getQueriesData<ChatMessageView[]>({
- queryKey: ['messages', event.sessionId],
- });
let matchedCachedMessage = false;
let editedLastMessage = false;
- for (const [key, list] of caches) {
- if (!list) continue;
- const next = applyMessageEdit(list, event);
- if (next === list) continue;
+ for (const [key, thread] of cachedSessionThreads(queryClient, event.sessionId, byMessageId(event.messageId))) {
+ // Position is asked of the merged thread, never of a page: pages are stored as the server
+ // returns them, newest-first, so the last row of one is its OLDEST message.
+ const editedIndex = thread.findIndex(byMessageId(event.messageId));
+ if (editedIndex === -1) continue;
matchedCachedMessage = true;
- queryClient.setQueryData(key, next);
+ updateCachedMessages(queryClient, key, list => applyMessageEdit(list, event));
- // Message caches are chronological; only editing the final row changes the sidebar preview.
- // Confirm the cache belongs to the event chat before touching that summary.
- const cachedChatId = Array.isArray(key) && typeof key[2] === 'string' ? key[2] : undefined;
- const editedIndex = list.findIndex(m => m.id === event.messageId || m.waMessageId === event.messageId);
- if (cachedChatId === event.chatId && editedIndex === list.length - 1) editedLastMessage = true;
+ // Only editing the newest row changes the sidebar preview. Confirm the thread belongs to
+ // the event chat before touching that summary.
+ if (key[2] === event.chatId && editedIndex === thread.length - 1) editedLastMessage = true;
}
if (editedLastMessage) {
setChats(previous =>
diff --git a/dashboard/src/test-helpers/socket-io-double.ts b/dashboard/src/test-helpers/socket-io-double.ts
new file mode 100644
index 000000000..d650fae42
--- /dev/null
+++ b/dashboard/src/test-helpers/socket-io-double.ts
@@ -0,0 +1,72 @@
+/**
+ * Stand-in for `socket.io-client` under the bare `node --test` runner, aliased by
+ * vite-shim-hooks.mjs.
+ *
+ * A test cannot use the real client: there is no server, so `io()` dials and fails, and nothing can
+ * push a server event into the page. That left every realtime handler in the dashboard untested —
+ * which is how a chat cache read as the wrong shape reached review with green CI. This double never
+ * dials; it records listeners and lets a test deliver an envelope with `lastSocket().receive(...)`.
+ *
+ * Tests that do not set `sessionStorage['openwa_api_key']` never reach `io()` at all (useWebSocket
+ * bails first), so aliasing this in changes nothing for them.
+ */
+
+type Listener = (...args: unknown[]) => void;
+
+class FakeSocket {
+ connected = true;
+ private listeners = new Map<string, Set<Listener>>();
+ /** The manager namespace (`socket.io.on('reconnect_failed', …)`). */
+ readonly io = { on: (): void => undefined };
+
+ on(event: string, listener: Listener): this {
+ const set = this.listeners.get(event) ?? new Set<Listener>();
+ set.add(listener);
+ this.listeners.set(event, set);
+ // The real client fires 'connect' asynchronously after the handshake; do it on registration so
+ // a page that gates its subscribe on connection reaches the same state.
+ if (event === 'connect') queueMicrotask(() => listener());
+ return this;
+ }
+
+ off(event: string, listener?: Listener): this {
+ if (listener === undefined) this.listeners.delete(event);
+ else this.listeners.get(event)?.delete(listener);
+ return this;
+ }
+
+ emit(): this {
+ return this;
+ }
+
+ disconnect(): this {
+ this.connected = false;
+ return this;
+ }
+
+ /** Deliver a server frame to whatever the page registered for `event`. */
+ receive(event: string, ...args: unknown[]): void {
+ for (const listener of this.listeners.get(event) ?? []) listener(...args);
+ }
+}
+
+let last: FakeSocket | null = null;
+
+export function io(): FakeSocket {
+ last = new FakeSocket();
+ return last;
+}
+
+/** The socket the page most recently opened, or null if it never got as far as opening one. */
+export function lastSocket(): FakeSocket | null {
+ return last;
+}
+
+export function resetSocketDouble(): void {
+ last = null;
+}
+
+// A VALUE export, not `export type`: useWebSocket imports `Socket` from a value position, and only
+// files that also read `import.meta.env` go through the transpiler that would elide it.
+export { FakeSocket as Socket };
+export default { io };
diff --git a/dashboard/src/test-helpers/vite-shim-hooks.mjs b/dashboard/src/test-helpers/vite-shim-hooks.mjs
index f8804cf8e..9a28a0e8f 100644
--- a/dashboard/src/test-helpers/vite-shim-hooks.mjs
+++ b/dashboard/src/test-helpers/vite-shim-hooks.mjs
@@ -23,7 +23,11 @@ const ts = require('typescript');
const RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.js', '.mjs', '.json'];
+// socket.io-client is swapped for a double that never dials — see test-helpers/socket-io-double.ts.
+const SOCKET_DOUBLE = new URL('./socket-io-double.ts', import.meta.url).href;
+
export async function resolve(specifier, context, nextResolve) {
+ if (specifier === 'socket.io-client') return { url: SOCKET_DOUBLE, shortCircuit: true };
try {
return await nextResolve(specifier, context);
} catch (error) {
diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.ts
index 2f15902a4..97335e4f9 100644
--- a/dashboard/src/utils/chatMessages.ts
+++ b/dashboard/src/utils/chatMessages.ts
@@ -65,9 +65,11 @@ export function mergeChatMessages(db: ChatMessage[], history: ChatMessage[]): Ch
* renderable (thread + lightbox). Count-based (not byte-based): payloads are bounded upstream
* by the backend's media size cap.
*
- * The cap must cover the fetch window: useChatMessages loads a 100-message slice with media, so a
- * smaller cap strips payloads INSIDE the window the user can scroll to — and with staleTime:
- * Infinity there is no refetch path, leaving a dead-end 📎 placeholder for media that was fetched.
+ * The cap bounds the RENDERED set, not the fetch window: useChatMessages pages, so a thread scrolled
+ * back far enough holds several 100-row pages and the older payloads inside the scrollable window
+ * fall back to the 📎 placeholder, whose download button still works. Do not scale `keep` with the
+ * page count to close that gap — the rendered set is exactly where a payload costs a second `data:`
+ * URI copy and a decoded bitmap, so scaling removes the bound this exists to enforce.
*/
export const MEDIA_PAYLOAD_CACHE_LIMIT = 100;
@@ -246,6 +248,35 @@ export function removeMessageById(list: ChatMessageView[], id: string): ChatMess
return list.filter(m => m.id !== id);
}
+/** Does this row carry the given WhatsApp identity, under either of the two ids it can be keyed by? */
+export const byMessageId =
+ (messageId: string) =>
+ (m: ChatMessageView): boolean =>
+ m.id === messageId || m.waMessageId === messageId;
+
+/**
+ * Patch every row a WhatsApp identity names, leaving the array untouched when none match.
+ *
+ * Every match is patched, not just the first: a paged cache can hold the persisted row and its live
+ * copy on different pages (see findRevokedIndex for why the two are keyed differently), and
+ * patching only the one the merged view preferred would leave the other stale.
+ */
+export function patchMatchingMessage(
+ list: ChatMessageView[],
+ messageId: string,
+ patch: (message: ChatMessageView) => ChatMessageView,
+): ChatMessageView[] {
+ const isMatch = byMessageId(messageId);
+ let changed = false;
+ const next = list.map(m => {
+ if (!isMatch(m)) return m;
+ const patched = patch(m);
+ if (patched !== m) changed = true;
+ return patched;
+ });
+ return changed ? next : list;
+}
+
/**
* Locate the message a `message.revoked` event refers to. Returns -1 if it isn't cached.
*
@@ -262,21 +293,22 @@ export function removeMessageById(list: ChatMessageView[], id: string): ChatMess
* whose `waMessageId` is also undefined.
*/
export function findRevokedIndex(list: ChatMessageView[], event: { id: string; revokedId?: string }): number {
- const matches = (m: ChatMessageView, candidate: string): boolean => m.id === candidate || m.waMessageId === candidate;
- return list.findIndex(m => matches(m, event.id) || (event.revokedId !== undefined && matches(m, event.revokedId)));
+ const byId = byMessageId(event.id);
+ const byRevokedId = event.revokedId !== undefined ? byMessageId(event.revokedId) : undefined;
+ return list.findIndex(m => byId(m) || (byRevokedId?.(m) ?? false));
}
/**
- * Replace the displayed body of a cached WhatsApp message after a `message.edited` event. Persisted
- * rows use a local UUID in `id` and the WhatsApp identity in `waMessageId`; live rows often use the
- * WhatsApp identity for both, so both candidates are required. Returns the original array on a miss.
+ * Replace the displayed body of a cached WhatsApp message after a `message.edited` event. Both id
+ * candidates are matched, for the reason given on findRevokedIndex. Returns the original array on
+ * a miss.
*/
export function applyMessageEdit(
list: ChatMessageView[],
event: { messageId: string; body: string },
): ChatMessageView[] {
if (!event.messageId) return list;
- const idx = list.findIndex(m => m.id === event.messageId || m.waMessageId === event.messageId);
+ const idx = list.findIndex(byMessageId(event.messageId));
if (idx === -1) return list;
const next = list.slice();
next[idx] = { ...next[idx], body: event.body };
diff --git a/dashboard/src/utils/messagePages.test.ts b/dashboard/src/utils/messagePages.test.ts
index e808aa849..0a014e71c 100644
--- a/dashboard/src/utils/messagePages.test.ts
+++ b/dashboard/src/utils/messagePages.test.ts
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
import { dbRowsFetched, nextMessagePageParam, upsertIntoPages, type MessagePage } from './messagePages.ts';
import type { ChatMessageView } from './chatMessages.ts';
+const PAGE_SIZE = 100;
+
const msg = (id: string, extra: Partial<ChatMessageView> = {}): ChatMessageView =>
({
id,
@@ -17,37 +19,55 @@ const msg = (id: string, extra: Partial<ChatMessageView> = {}): ChatMessageView
...extra,
}) as ChatMessageView;
-const page = (db: ChatMessageView[], total: number, history: ChatMessageView[] = []): MessagePage => ({
+/** `fetched` defaults to a full page, i.e. "the server had at least this many more". */
+const page = (db: ChatMessageView[], fetched = PAGE_SIZE, history: ChatMessageView[] = []): MessagePage => ({
db,
history,
- total,
+ fetched,
});
+const rows = (count: number, prefix: string): ChatMessageView[] =>
+ Array.from({ length: count }, (_, i) => msg(`${prefix}${i}`));
+
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')])];
+ const pages = [page([msg('a'), msg('b')], PAGE_SIZE, [msg('h1'), msg('h2'), msg('h3')])];
assert.equal(dbRowsFetched(pages), 2);
- assert.equal(nextMessagePageParam(pages), 2);
+ assert.equal(nextMessagePageParam(pages, PAGE_SIZE), 2);
});
test('the cursor accumulates across pages', () => {
- const pages = [page([msg('a'), msg('b')], 10), page([msg('c')], 10)];
+ const pages = [page([msg('a'), msg('b')]), page([msg('c')])];
- assert.equal(nextMessagePageParam(pages), 3);
+ assert.equal(nextMessagePageParam(pages, PAGE_SIZE), 3);
});
-test('paging stops once the chat total is covered', () => {
- assert.equal(nextMessagePageParam([page([msg('a'), msg('b')], 2)]), undefined);
+test('paging stops once a page comes back short of what it asked for', () => {
+ assert.equal(nextMessagePageParam([page([msg('a'), msg('b')], 2)], PAGE_SIZE), undefined);
});
test('paging stops on an empty chat rather than asking for offset 0 forever', () => {
- assert.equal(nextMessagePageParam([page([], 0)]), undefined);
+ assert.equal(nextMessagePageParam([page([], 0)], PAGE_SIZE), undefined);
+});
+
+test('live messages move the cursor without ending the paging', () => {
+ // The bug this locks out: terminating on "rows held >= the chat's row total" compares a count
+ // that grows (every live arrival is merged into page 0) against a total frozen at the last
+ // fetch. On a 105-row chat the two met after five live messages and the five oldest rows became
+ // unreachable until a reload. The offset SHOULD follow the arrivals — each server insert shifts
+ // the window by one — so only the stopping rule changes.
+ let pages = [page(rows(PAGE_SIZE, 'db-'), PAGE_SIZE)];
+ assert.equal(nextMessagePageParam(pages, PAGE_SIZE), 100);
+
+ for (let i = 0; i < 5; i++) pages = upsertIntoPages(pages, msg(`live-${i}`));
+
+ assert.equal(nextMessagePageParam(pages, PAGE_SIZE), 105);
});
test('a live message lands on the newest page', () => {
- const pages = [page([msg('new')], 3), page([msg('old')], 3)];
+ const pages = [page([msg('new')]), page([msg('old')])];
const result = upsertIntoPages(pages, msg('live'));
@@ -64,7 +84,7 @@ test('a live message lands on the newest page', () => {
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 pages = [page([msg('new')]), page([msg('old', { status: 'sent' })])];
const result = upsertIntoPages(pages, msg('old', { status: 'read' }));
@@ -74,7 +94,7 @@ test('a message already held by an older page is merged there, not duplicated',
});
test('an optimistic placeholder is dropped from whichever page holds it', () => {
- const pages = [page([msg('tmp-1')], 2)];
+ const pages = [page([msg('tmp-1')])];
const result = upsertIntoPages(pages, msg('real-1'), 'tmp-1');
@@ -87,7 +107,7 @@ test('an optimistic placeholder is dropped from whichever page holds it', () =>
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 pages = [page([msg('tmp-1'), msg('real-1')])];
const result = upsertIntoPages(pages, msg('real-1', { status: 'sent' }), 'tmp-1');
diff --git a/dashboard/src/utils/messagePages.ts b/dashboard/src/utils/messagePages.ts
index 8e6ba307d..e89614807 100644
--- a/dashboard/src/utils/messagePages.ts
+++ b/dashboard/src/utils/messagePages.ts
@@ -8,8 +8,11 @@ import { mergeOrAppend, type ChatMessageView } from './chatMessages.ts';
export interface MessagePage {
db: ChatMessageView[];
history: ChatMessageView[];
- /** Total DB rows for this chat (getManyAndCount) — says whether an older page exists. */
- total: number;
+ /**
+ * Rows this page's fetch RETURNED, recorded before any live arrival is merged in. `db.length`
+ * drifts upward as messages land in page 0, which is why termination cannot be read from it.
+ */
+ fetched: number;
}
/** DB rows fetched across every page so far — the offset the next page asks for. */
@@ -18,15 +21,17 @@ export function dbRowsFetched(pages: MessagePage[]): number {
}
/**
- * Offset of the next older page, or undefined once the chat's rows are covered.
+ * Offset of the next older page, or undefined once the oldest page came back short.
*
- * 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.
+ * The offset counts DB rows including live arrivals — each server insert shifts the window by one,
+ * and rendered length would count engine-history items the DB never returned. Termination cannot
+ * use that same growing count against the chat's frozen row total, which meets it a few live
+ * messages early and strands the oldest rows.
*/
-export function nextMessagePageParam(pages: MessagePage[]): number | undefined {
- const fetched = dbRowsFetched(pages);
- const total = pages[pages.length - 1]?.total ?? 0;
- return fetched < total ? fetched : undefined;
+export function nextMessagePageParam(pages: MessagePage[], pageSize: number): number | undefined {
+ const oldest = pages[pages.length - 1];
+ if (oldest === undefined || oldest.fetched < pageSize) return undefined;
+ return dbRowsFetched(pages);
}
const messageKey = (m: ChatMessageView): string => m.waMessageId ?? m.id;