Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): replay queued writes on fetch settle, not remount, and cover the gaps behind it

JuanGalzeranof76756ddeb4c
diff --git a/dashboard/src/hooks/useChatMessages.ts b/dashboard/src/hooks/useChatMessages.ts
index e04c5ab40..ecfae3fe9 100644
--- a/dashboard/src/hooks/useChatMessages.ts
+++ b/dashboard/src/hooks/useChatMessages.ts
@@ -3,6 +3,7 @@ import {
useQueryClient,
type InfiniteData,
type UseInfiniteQueryResult,
+ type QueryCacheNotifyEvent,
} from '@tanstack/react-query';
import type { QueryClient } from '@tanstack/react-query';
import { useEffect } from 'react';
@@ -33,7 +34,7 @@ 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
+ * The one flat chronological view of a paged cache. A single page is ascending but partial, so
* neither a message's position nor its absence can be read from one.
*/
export function flattenMessagePages(data: MessagesData): ChatMessageView[] {
@@ -51,9 +52,10 @@ export function flattenMessagePages(data: MessagesData): ChatMessageView[] {
* 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.
+ * Base64 media payloads are bounded twice: `mergeOrAppend` caps each page's `db` as messages land
+ * in it (so a media-heavy page 0 can't grow the cache unbounded), and `select` caps the flattened,
+ * correctly-ordered thread again for what actually renders — the two bounds cover the cache and the
+ * viewport respectively, and neither alone would cover both.
*/
export function useChatMessages(
sessionId: string,
@@ -75,7 +77,10 @@ export function useChatMessages(
if (dbRes.status === 'rejected' && (!wantsHistory || historyRes.status === 'rejected')) throw dbRes.reason;
const db = dbRes.status === 'fulfilled' ? dbRes.value : { messages: [] };
const history = historyRes.status === 'fulfilled' ? historyRes.value.map(mapEngineHistoryMessage) : [];
- return { db: db.messages, history, fetched: db.messages.length };
+ // The gateway answers newest-first (createdAt DESC); reversed here so `page.db` is ascending
+ // like the flattened thread. mergeOrAppend's cap strips from the front of an ascending list —
+ // storing pages in server order would make it strip the newest payloads first.
+ return { db: [...db.messages].reverse(), history, fetched: db.messages.length };
},
getNextPageParam: (_lastPage, allPages) => nextMessagePageParam(allPages, MESSAGE_PAGE_SIZE),
// Consumers keep seeing one flat chronological list; paging stays inside the cache.
@@ -88,14 +93,14 @@ export function useChatMessages(
// 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.
- //
- // 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.
+ // that window would leave the thread for good. writeMessagesCache queues those writes and
+ // schedules their replay for the moment the fetch settles (see scheduleReplayOnSettle) — not for
+ // whenever this hook next happens to mount, which is too late: another writer (the composer's own
+ // send reconciling, a socket event routed through cachedSessionThreads to a chat that is not even
+ // open) can land on the cache between the fetch settling and a remount, and a replay fired only on
+ // remount would stomp that newer write with the stale queued one. This effect stays as a second
+ // chance for the same key in case the fetch had already settled before any write ever queued for
+ // it — a normal case, and a no-op here since the queue is empty by then.
const { isFetching } = query;
useEffect(() => {
if (isFetching) return;
@@ -113,9 +118,44 @@ interface PendingWrite {
// Module scope because the helpers below are plain functions with no component to hang state on.
const writesLostToFetch = new Map<string, PendingWrite[]>();
+// One queryCache subscription per key with a queue outstanding, so replay fires the instant that
+// key's fetch settles rather than whenever a consumer next mounts — see scheduleReplayOnSettle.
+const settleSubscriptions = new Map<string, () => void>();
const pendingKey = (key: MessagesQueryKey): string => JSON.stringify(key);
+const sameQueryKey = (a: readonly unknown[], b: MessagesQueryKey): boolean =>
+ a.length === b.length && a.every((part, i) => part === b[i]);
+
+/**
+ * Fire replayWritesLostToFetch for `key` the moment its query stops fetching, independent of
+ * whether any component watching it is mounted. Self-unsubscribes on that event or on the query
+ * being removed from the cache entirely (gcTime elapsed with nothing open) — replaying onto a
+ * query that no longer exists would just reseed a phantom entry, which writeMessagesCache's own
+ * "never seed a slice" rule exists to prevent.
+ *
+ * Idempotent to call redundantly: only takes effect while no subscription is already tracked for
+ * this key (writeMessagesCache only calls it when the queue transitions from empty to non-empty).
+ */
+function scheduleReplayOnSettle(queryClient: QueryClient, key: MessagesQueryKey): void {
+ const id = pendingKey(key);
+ if (settleSubscriptions.has(id)) return;
+ const unsubscribe = queryClient.getQueryCache().subscribe((event: QueryCacheNotifyEvent) => {
+ if (!sameQueryKey(event.query.queryKey, key)) return;
+ if (event.type === 'removed') {
+ settleSubscriptions.delete(id);
+ unsubscribe();
+ writesLostToFetch.delete(id);
+ return;
+ }
+ if (event.query.state.fetchStatus === 'fetching') return;
+ settleSubscriptions.delete(id);
+ unsubscribe();
+ replayWritesLostToFetch(queryClient, key);
+ });
+ settleSubscriptions.set(id, unsubscribe);
+}
+
/**
* Apply one change to a chat's paged cache, recording it for replay when a page is in flight.
*
@@ -134,8 +174,10 @@ function writeMessagesCache(
queryClient.setQueryData<MessagesData>(key, old => (old === undefined ? undefined : apply(old)));
if (state.fetchStatus !== 'fetching') return;
const id = pendingKey(key);
+ const queued = writesLostToFetch.get(id) ?? [];
const wrote = queryClient.getQueryData<MessagesData>(key);
- writesLostToFetch.set(id, [...(writesLostToFetch.get(id) ?? []), { apply, wrote }]);
+ writesLostToFetch.set(id, [...queued, { apply, wrote }]);
+ if (queued.length === 0) scheduleReplayOnSettle(queryClient, key);
}
/**
@@ -146,6 +188,11 @@ function writeMessagesCache(
* 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.
+ *
+ * Called right as the fetch that could have clobbered the queue settles (scheduleReplayOnSettle),
+ * so this identity check is comparing against the immediately-landed page, before any OTHER writer
+ * gets a turn — that ordering is what keeps a later, unrelated write from being overwritten by a
+ * stale replay that only fired once some consumer happened to remount.
*/
export function replayWritesLostToFetch(queryClient: QueryClient, key: MessagesQueryKey): void {
const id = pendingKey(key);
diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.ts
index 2bb2aecdf..5978acf1d 100644
--- a/dashboard/src/hooks/useChatScrollPosition.ts
+++ b/dashboard/src/hooks/useChatScrollPosition.ts
@@ -55,6 +55,10 @@ export function decideRestoreTarget(
* top"). While pinned, each `onMediaLoad` re-pins to the bottom; the pin
* releases as soon as the USER scrolls away from the bottom (and re-arms when
* they scroll back), so late-decoding media never yanks a reading user.
+ * - Reading further back: the same late-decode growth, above a viewport that is
+ * NOT pinned to the bottom, holds the user's position instead of re-pinning —
+ * `onMediaLoad`'s third branch, since a decode there has no requesting call to
+ * snapshot a "before" height from the way `onOlderMessagesRequested` does.
*
* Mount the returned `containerRef` on the scroll container (the `.room-messages`
* div in Chats.tsx). The Map of saved positions lives in a ref so it doesn't
@@ -95,6 +99,9 @@ export function useChatScrollPosition(
const prevScrollHeightRef = useRef<number>(0);
const awaitingOlderPageRef = useRef<boolean>(false);
const wasFetchingOlderRef = useRef<boolean>(false);
+ // The container's height as of the last commit this hook has accounted for — see the "always
+ // sync" layout effect and onMediaLoad's unpinned branch below.
+ const lastCommittedHeightRef = useRef<number>(0);
const writeScrollTop = useCallback((el: HTMLDivElement, top: number) => {
const before = el.scrollTop;
@@ -188,7 +195,25 @@ export function useChatScrollPosition(
// 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);
+ if (grew > 0) {
+ const corrected = el.scrollTop + grew;
+ writeScrollTop(el, corrected);
+ // writeScrollTop marks this as a programmatic write, so the scroll listener's own
+ // scrollMap.set skips it — without saving it here too, the map keeps whatever the user's
+ // last REAL scroll left there, which is necessarily above the paging threshold (that is
+ // what triggered this fetch). Leaving without scrolling again and coming back would restore
+ // to that stale, too-high spot instead of the corrected one actually being read.
+ if (activeChatId !== null) scrollMap.current.set(activeChatId, corrected);
+ }
+ });
+
+ // Keeps lastCommittedHeightRef in sync with every commit's actual height, so onMediaLoad's
+ // unpinned branch below always has a same-commit baseline to diff a decode's growth against —
+ // no dep array, same reasoning as the scroll-listener effect above: it must run every render to
+ // stay current, not just when some particular prop happens to change.
+ useLayoutEffect(() => {
+ const el = containerRef.current;
+ if (el) lastCommittedHeightRef.current = el.scrollHeight;
});
const onOlderMessagesRequested = useCallback(() => {
@@ -220,6 +245,13 @@ export function useChatScrollPosition(
// while a 'saved' restore is pending, each decode RE-APPLIES the saved scrollTop (the first write
// was clamped to the pre-decode scrollHeight). A user scroll clears both, so late-decoding media
// never yanks a reading user.
+ //
+ // Reading further back through media-heavy history is the third case: not pinned, nothing
+ // pending. A decode above the viewport still grows the thread with no reserved box (there is no
+ // width/height in the media metadata to size one from up front), pushing what the user is
+ // reading down exactly like an unabsorbed older-page prepend — held the same way, against the
+ // last height this hook has seen rather than a snapshot taken at some fixed "request" moment,
+ // since there is no equivalent request event for a decode to hang one on.
const onMediaLoad = useCallback(() => {
const pending = pendingRestoreRef.current;
if (pending !== null) {
@@ -229,12 +261,24 @@ export function useChatScrollPosition(
});
return;
}
- if (!pinnedRef.current) return;
+ if (pinnedRef.current) {
+ requestAnimationFrame(() => {
+ const cur = containerRef.current;
+ if (cur && pinnedRef.current) pinToBottom(cur);
+ });
+ return;
+ }
requestAnimationFrame(() => {
const cur = containerRef.current;
- if (cur && pinnedRef.current) pinToBottom(cur);
+ if (!cur) return;
+ const grew = cur.scrollHeight - lastCommittedHeightRef.current;
+ if (grew <= 0) return;
+ const corrected = cur.scrollTop + grew;
+ writeScrollTop(cur, corrected);
+ lastCommittedHeightRef.current = cur.scrollHeight;
+ if (activeChatId !== null) scrollMap.current.set(activeChatId, corrected);
});
- }, [pinToBottom, writeScrollTop]);
+ }, [activeChatId, pinToBottom, writeScrollTop]);
return { containerRef, onMessageAppended, onMediaLoad, onOlderMessagesRequested };
}
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index 3912ef435..1cbd6b74a 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -126,6 +126,8 @@ const PAGED_OLDEST = Array.from({ length: 20 }, (_, i) =>
// Hold the older page open so the spinner commit and the landing commit stay distinct.
let olderPageGate: Promise<void> | null = null;
+// When true, an older-page request (any offset but 0) answers 500 instead of a page.
+let olderPageFails = false;
function holdOlderPage(): () => void {
let release!: () => void;
@@ -135,6 +137,17 @@ function holdOlderPage(): () => void {
return release;
}
+// Hold a text send open, so a test can land it at a chosen moment relative to an older-page fetch.
+let sendGate: Promise<void> | null = null;
+
+function holdSend(): () => void {
+ let release!: () => void;
+ sendGate = 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}`;
@@ -248,8 +261,16 @@ function installFetchStub(): void {
const query = new URLSearchParams(path.slice(path.indexOf('?') + 1));
if (query.get('chatId') === CHAT_2.id) {
const isFirstPage = Number(query.get('offset')) === 0;
+ if (!isFirstPage && olderPageFails) return Promise.resolve(jsonResponse({ message: 'boom' }, 500));
const messages = isFirstPage ? PAGED_NEWEST : PAGED_OLDEST;
- const answer = () => jsonResponse({ messages, total: PAGED_NEWEST.length + PAGED_OLDEST.length });
+ // `total` deliberately does NOT equal the 120 rows actually served (PAGED_NEWEST.length +
+ // PAGED_OLDEST.length). The current termination rule never reads this field — it stops on a
+ // page short of what it asked for — so the value doesn't matter to it either way. It matters
+ // to the TEST: a `total` that happened to equal the served row count let a reverted, WRONG
+ // rule (`rows held >= total`) terminate correctly by coincidence, so the "pulls exactly one
+ // older page, then stops" assertion below could not tell a working implementation from a
+ // broken one. Set far above what is served, that coincidence is gone.
+ const answer = () => jsonResponse({ messages, total: 500 });
const gate = isFirstPage ? null : olderPageGate;
return gate ? gate.then(answer) : Promise.resolve(answer());
}
@@ -273,7 +294,8 @@ function installFetchStub(): void {
return Promise.resolve(jsonResponse({ success: true }));
}
if (method === 'POST' && path === `/api/sessions/${SESSION.id}/messages/send-text`) {
- return Promise.resolve(jsonResponse({ messageId: 'wamid.out.1', timestamp: 1_700_000_100 }));
+ const send = () => jsonResponse({ messageId: 'wamid.out.1', timestamp: 1_700_000_100 });
+ return sendGate ? sendGate.then(send) : Promise.resolve(send());
}
if (method === 'POST' && path === `/api/sessions/${SESSION.id}/status/send-text`) {
return Promise.resolve(jsonResponse({ success: true }));
@@ -327,6 +349,8 @@ afterEach(() => {
// A gate left held would stall the next test's fetch forever.
mediaGates.clear();
olderPageGate = null;
+ sendGate = null;
+ olderPageFails = false;
});
function renderChats(): { container: HTMLElement } {
@@ -667,6 +691,32 @@ test('scrolling to the top of a long thread pulls exactly one older page, then s
assert.equal(countPagedMessagesFetches(), 2);
});
+test('a failed older-page fetch does not blank an already-loaded thread', async () => {
+ const { fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ const { container } = renderChats();
+
+ const thread = await openPagedChat(container);
+ olderPageFails = true;
+ makeScrollable(thread, 0);
+ fireEvent.scroll(thread);
+
+ // The regression: ChatThread tested messagesError before messages.length, so this 500 replaced
+ // the 100 already-loaded bubbles with the full-screen error placeholder — and the collapsed
+ // container could then never regain enough height to retry by scrolling.
+ await waitFor(() => assert.ok(within(thread).queryByText('paged message 119')));
+ assert.equal(within(thread).queryByText(/couldn.t load messages/i), null, 'the full-screen error must not render');
+ assert.equal(container.querySelector('.messages-empty'), null, 'the full-screen error must not render');
+
+ // The failure shows inline, where the spinner would have — with a retry hint, since the
+ // container never collapsed and scrolling up again is still possible.
+ await waitFor(() => {
+ const inline = thread.querySelector('.messages-loading-older');
+ assert.ok(inline, 'expected an inline failure indicator');
+ assert.match(inline!.textContent ?? '', /couldn.t load older messages/i);
+ });
+});
+
test('a delivery ack reaches a message held by an older page', async () => {
const { fireEvent, within, waitFor } = rtl;
resetFetchCalls();
@@ -731,6 +781,41 @@ test('the reading position is held across the commit that lands an older page',
assert.equal(thread.scrollTop, PAGED_OLDEST.length * BUBBLE_PX);
});
+test('leaving without scrolling again restores the corrected position, not the stale pre-correction one', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ const { container } = renderChats();
+
+ const thread = await openPagedChat(container);
+
+ // The only scroll event this test fires — the position the scroll listener's own map records —
+ // stays at 0 throughout. Everything after this is the older-page CORRECTION writing scrollTop
+ // directly (a programmatic write, which the listener does not see), not a further user scroll.
+ const releaseOlderPage = holdOlderPage();
+ makeScrollable(thread, 0);
+ fireEvent.scroll(thread);
+ await waitFor(() => assert.ok(thread.querySelector('.messages-loading-older')));
+
+ releaseOlderPage();
+ await within(thread).findByText('paged message 0');
+ await waitFor(() => assert.equal(thread.querySelector('.messages-loading-older'), null));
+
+ const corrected = thread.scrollTop;
+ assert.ok(corrected > 0, 'expected the older-page correction to have moved scrollTop off 0');
+
+ fireEvent.click(await screen.findByText('Alice'));
+ await within(container.querySelector('.room-header') as HTMLElement).findByText('Alice');
+
+ // Back to Carol, with no scroll event fired in between. The regression: the correction above
+ // writes scrollTop directly and skips the scroll-listener's own scrollMap.set (it is a
+ // programmatic write, not a user scroll), so without saving it explicitly the per-chat map
+ // still holds the stale value from the one real scroll this test fired, at 0 — landing the
+ // reader roughly a page above the row they were actually reading.
+ fireEvent.click(await screen.findByText('Carol'));
+ await within(thread).findByText('paged message 0');
+ assert.equal(thread.scrollTop, corrected);
+});
+
test('a message arriving while an older page is in flight survives the page landing', async () => {
const { fireEvent, within, waitFor } = rtl;
resetFetchCalls();
@@ -824,3 +909,49 @@ test('a write during an in-flight older page survives leaving and returning to t
await within(reopened).findByText('paged message 0');
await waitFor(() => assert.equal(within(reopened).getAllByText('arrived while switching away').length, 1));
});
+
+test('a send that reconciles after the older page has already settled does not resurrect the placeholder', 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')));
+
+ // Send while the older page is still in flight, so the optimistic append queues behind it —
+ // same as the write the previous test covers. The send's own HTTP response is held separately.
+ const releaseSend = holdSend();
+ const input = screen.getByPlaceholderText('Type a message...') as HTMLInputElement;
+ fireEvent.change(input, { target: { value: 'race test message' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));
+ await within(thread).findByText('race test message');
+
+ // Leave before either settles.
+ fireEvent.click(await screen.findByText('Alice'));
+ await within(container.querySelector('.room-header') as HTMLElement).findByText('Alice');
+
+ // The order that matters: the older page lands FIRST — replay fires immediately (not on
+ // remount), reapplying the queued optimistic append onto the just-landed page. Only THEN does
+ // the send resolve, reconciling directly onto what is now an idle cache (nothing left to queue
+ // behind). If replay instead waited for a remount, it would still be pending when this second,
+ // independent write landed — and firing later, on return, would replay the stale optimistic
+ // append over the reconciled result, putting the temp placeholder back beside the real message.
+ releaseOlderPage();
+ await flush();
+ releaseSend();
+ await waitFor(() => assert.equal(countFetchCalls('POST', `/api/sessions/${SESSION.id}/messages/send-text`), 1));
+ await flush();
+
+ fireEvent.click(await screen.findByText('Carol'));
+ const reopened = container.querySelector('.room-messages') as HTMLElement;
+ await within(reopened).findByText('paged message 119');
+
+ const bubbles = within(reopened).getAllByText('race test message');
+ assert.equal(bubbles.length, 1, 'expected exactly one bubble — a resurrected placeholder would show a second');
+ const icon = bubbles[0].closest('.message-bubble')?.querySelector('.message-status-icon');
+ assert.ok(icon?.classList.contains('sent'), 'expected the reconciled (sent) row, not a reverted pending ghost');
+});
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 8cccd9329..d9ecb30f7 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -481,8 +481,8 @@ export function Chats() {
let matchedCachedMessage = false;
let editedLastMessage = false;
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.
+ // Position is asked of the merged thread, never of a page: pages carry only a fraction of
+ // the chat each, so "is this the last message" is only ever answerable from the whole thing.
const editedIndex = thread.findIndex(byMessageId(event.messageId));
if (editedIndex === -1) continue;
matchedCachedMessage = true;
diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.ts
index cf451c900..aa727607a 100644
--- a/dashboard/src/utils/chatMessages.ts
+++ b/dashboard/src/utils/chatMessages.ts
@@ -206,13 +206,16 @@ 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). 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.
+ * 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.
+ *
+ * Requires an ASCENDING (oldest-first) `list` — the cap strips from the front, so a caller holding
+ * a `createdAt DESC` page would need to reverse it first, not call this directly on server order.
*/
-export function mergeOrAppendUncapped(list: ChatMessageView[], incoming: ChatMessageView): ChatMessageView[] {
+export function mergeOrAppend(list: ChatMessageView[], incoming: ChatMessageView): ChatMessageView[] {
const idx = list.findIndex(m => msgKey(m) === msgKey(incoming));
- if (idx === -1) return [...list, incoming];
+ if (idx === -1) return capMediaPayloads([...list, incoming]);
const existing = list[idx];
const next = list.slice();
next[idx] = {
@@ -222,16 +225,7 @@ export function mergeOrAppendUncapped(list: ChatMessageView[], incoming: ChatMes
status: mergeDeliveryStatus(existing.status, incoming.status) ?? incoming.status,
metadata: mergeMessageMetadata(existing.metadata, incoming.metadata),
};
- 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));
+ return capMediaPayloads(next);
}
/**
diff --git a/dashboard/src/utils/messagePages.test.ts b/dashboard/src/utils/messagePages.test.ts
index 6ad347d73..17a98f5e4 100644
--- a/dashboard/src/utils/messagePages.test.ts
+++ b/dashboard/src/utils/messagePages.test.ts
@@ -1,7 +1,7 @@
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';
+import { MEDIA_PAYLOAD_CACHE_LIMIT, type ChatMessageView } from './chatMessages.ts';
const PAGE_SIZE = 100;
@@ -29,6 +29,9 @@ const page = (db: ChatMessageView[], fetched = PAGE_SIZE, history: ChatMessageVi
const rows = (count: number, prefix: string): ChatMessageView[] =>
Array.from({ length: count }, (_, i) => msg(`${prefix}${i}`));
+const mediaMsg = (id: string, data: string): ChatMessageView =>
+ msg(id, { type: 'image', metadata: { media: { mimetype: 'image/jpeg', filename: `${id}.jpg`, data } } });
+
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.
@@ -84,6 +87,21 @@ test('a genuine DB row with no waMessageId still counts', () => {
assert.equal(dbRowsFetched(pages), 1);
});
+test('a media-heavy page 0 stays under the payload ceiling as live messages land', () => {
+ // page.db is stored ascending (reversed from the server's createdAt DESC at fetch time), so the
+ // cap that mergeOrAppend runs through upsertIntoPages strips the OLDEST payload of the page, not
+ // the newest -- the opposite of what stripping from the front would do on server order.
+ const full = [page(Array.from({ length: MEDIA_PAYLOAD_CACHE_LIMIT }, (_, i) => mediaMsg(`m-${i}`, `P${i}`)))];
+
+ const result = upsertIntoPages(full, mediaMsg('m-new', 'NEW'));
+
+ const withPayload = result[0].db.filter(m => m.metadata?.media?.data);
+ assert.equal(withPayload.length, MEDIA_PAYLOAD_CACHE_LIMIT);
+ assert.equal(result[0].db[0].metadata?.media?.data, undefined); // oldest stripped
+ assert.equal(result[0].db[0].metadata?.media?.omitted, true);
+ assert.equal(result[0].db[result[0].db.length - 1].metadata?.media?.data, 'NEW'); // newest kept
+});
+
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.ts
index 1d4932311..5353c3346 100644
--- a/dashboard/src/utils/messagePages.ts
+++ b/dashboard/src/utils/messagePages.ts
@@ -1,9 +1,11 @@
-import { mergeOrAppendUncapped, type ChatMessageView } from './chatMessages.ts';
+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.
+ * One fetched slice of a chat's history. `db` is stored ASCENDING (oldest-first) — reversed from the
+ * server's `createdAt DESC` at fetch time — so mergeOrAppend's payload cap, which strips from the
+ * front, strips the oldest rather than the newest. `db` and `history` stay separate from each other
+ * 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[];
@@ -50,11 +52,9 @@ const messageKey = (m: ChatMessageView): string => m.waMessageId ?? m.id;
*
* 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.
+ * page only when no page does. mergeOrAppend's payload cap applies per page here, since page.db is
+ * ascending — this is what bounds page 0's raw base64 as live media arrives; the final cap in
+ * `select` bounds the rendered set, which is a different array by then and needs its own.
*/
export function upsertIntoPages(pages: MessagePage[], incoming: ChatMessageView, dropId?: string): MessagePage[] {
const trimmed = dropId
@@ -66,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: mergeOrAppendUncapped(page.db, incoming) } : page));
+ return trimmed.map((page, i) => (i === index ? { ...page, db: mergeOrAppend(page.db, incoming) } : page));
}