Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): open a chat at a message sent while it loads
Yudhi Armyndharis073ad2db715a
diff --git a/dashboard/src/hooks/useChatScrollPosition.render.test.ts b/dashboard/src/hooks/useChatScrollPosition.render.test.tsindex 338c68044..c74c3b1b7 100644--- a/dashboard/src/hooks/useChatScrollPosition.render.test.ts+++ b/dashboard/src/hooks/useChatScrollPosition.render.test.ts@@ -617,6 +617,59 @@ test('a message announced while its chat is still loading does not override wher}});+// A chat dropped from the cache reopens with a spinner, and the composer is live meanwhile: what the reader sends then+// lands with the first page, and the chat opens on it rather than on the spot they left.+test('a message the reader sends while a chat with a saved spot loads opens the chat at it', async () => {+ const { render, screen, fireEvent, cleanup } = rtl;+ cleanup();+ const g: Geometry = { height: 4600, top: 0 };+ const restore = installGeometry(g);+ try {+ const { rerender } = render(createElement(Probe, { chatId: 'A' }));+ const el = screen.getByTestId('thread');+ fireEvent.scroll(el);+ readerScrollsTo(el, 3000); // the spot the reader left in A+ rerender(createElement(Probe, { chatId: null }));++ g.height = CLIENT_HEIGHT;+ rerender(createElement(Probe, { chatId: 'A', loaded: false }));+ hook().onMessageAppended('outgoing');+ g.height = 4900; // the first page, with the message sent meanwhile+ rerender(createElement(Probe, { chatId: 'A', loaded: true }));+ assert.equal(el.scrollTop, g.height - CLIENT_HEIGHT, 'the message the reader sent was left below the fold');++ rerender(createElement(Probe, { chatId: 'B' })); // the reader leaves A at its bottom+ fireEvent.scroll(el);+ rerender(createElement(Probe, { chatId: 'A' }));+ assert.equal(el.scrollTop, g.height - CLIENT_HEIGHT, 'A reopened at the old spot instead of at the bottom');+ } finally {+ restore();+ }+});++test('a message sent in a loading chat the reader then left does not move the next chat', async () => {+ const { render, screen, fireEvent, cleanup } = rtl;+ cleanup();+ const g: Geometry = { height: 4600, top: 0 };+ const restore = installGeometry(g);+ try {+ const { rerender } = render(createElement(Probe, { chatId: 'B' }));+ const el = screen.getByTestId('thread');+ fireEvent.scroll(el);+ readerScrollsTo(el, 1000); // the spot the reader left in B+ rerender(createElement(Probe, { chatId: null }));++ g.height = CLIENT_HEIGHT;+ rerender(createElement(Probe, { chatId: 'A', loaded: false }));+ hook().onMessageAppended('outgoing');+ g.height = 4600;+ rerender(createElement(Probe, { chatId: 'B' })); // the reader opens B before A has loaded+ assert.equal(el.scrollTop, 1000, 'B did not open at the spot the reader left');+ } finally {+ restore();+ }+});+// ── Media decoding ───────────────────────────────────────────────────────────// Media has no box before it decodes, so a thread grows after it was positioned.diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.tsindex 0b96cec7a..c1dc0109f 100644--- a/dashboard/src/hooks/useChatScrollPosition.ts+++ b/dashboard/src/hooks/useChatScrollPosition.ts@@ -190,6 +190,8 @@ export function useChatScrollPosition(const wasFetchingOlderRef = useRef<boolean>(false);// The element the reader was on when the older page was requested; see the landing effect.const olderAnchorRef = useRef<{ node: Element; top: number } | null>(null);+ // The chat whose thread was still loading when the reader sent a message in it, until its restore decision.+ const sentWhileLoadingRef = useRef<string | null>(null);// Box height of each mounted media element, recorded at DOM insertion: the one moment a browser// guarantees is before the decode. A WeakMap so entries die with the nodes on a chat switch.const mediaHeights = useRef(new WeakMap<Element, number>());@@ -263,9 +265,15 @@ export function useChatScrollPosition(if (next !== prevChatIdRef.current) awaitingOlderPageRef.current = false;const decision = decideRestoreTarget(next, isLoaded, next !== null ? scrollMap.current.get(next) : undefined);+ // A message the reader sent while this chat loaded opens it at that message, the way a send in a loaded chat+ // scrolls to it. Only in the chat it was sent in: the next restore decision, in whichever chat, forgets it.+ const sentWhileLoading = sentWhileLoadingRef.current === next;+ if (decision.restore !== null) sentWhileLoadingRef.current = null;if (el) {- if (decision.restore === 'saved' && next !== null) {+ if (decision.restore !== null && sentWhileLoading) {+ followBottom(el);+ } else if (decision.restore === 'saved' && next !== null) {const saved = scrollMap.current.get(next);if (saved !== undefined) {pendingRestoreRef.current = saved; // re-applied on media loads until the user scrolls@@ -279,7 +287,7 @@ export function useChatScrollPosition(prevChatIdRef.current = next;loadedRef.current = isLoaded;- }, [activeChatId, isLoaded, pinToBottom, writeScrollTop]);+ }, [activeChatId, isLoaded, followBottom, 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@@ -367,8 +375,11 @@ export function useChatScrollPosition(// A chat that has not rendered its thread has nothing to follow: the restore decides where it opens. Nor has one// that is still on its way to a saved spot, for a message that arrives: the short, undecoded thread reads as at// the bottom, and following it would drop the saved spot the next decode puts the reader back on. A message the- // reader sends themselves always scrolls, saved spot or not.- if (!el || !loadedRef.current) return;+ // reader sends themselves always scrolls, saved spot or not, and one sent while the thread loads opens it there.+ if (!el || !loadedRef.current) {+ if (direction === 'outgoing') sentWhileLoadingRef.current = prevChatIdRef.current;+ return;+ }if (direction === 'incoming' && pendingRestoreRef.current !== null) return;const geometry = { scrollTop: el.scrollTop, scrollHeight: el.scrollHeight, clientHeight: el.clientHeight };if (decideScroll(direction, geometry) === 'preserve') return;diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsindex 09ad3b58b..f01433bcf 100644--- a/dashboard/src/pages/Chats.test.ts+++ b/dashboard/src/pages/Chats.test.ts@@ -3543,6 +3543,55 @@ test('a message sent from the page scrolls a chat reopened at its saved spot to}});+test('a message sent while a chat with a saved spot loads again opens the chat at it', async () => {+ const { screen, fireEvent, within, waitFor } = rtl;+ resetFetchCalls();+ // Forty more of Alice's messages, so her thread scrolls.+ firstPageExtra = Array.from({ length: 40 }, (_, i) => ({+ ...DB_MESSAGE,+ id: `db-extra-${i}`,+ waMessageId: `wamid.extra.${i}`,+ body: `alice extra ${i}`,+ timestamp: 1_700_000_100 + i,+ createdAt: new Date((1_700_000_100 + i) * 1000).toISOString(),+ }));+ const restoreGeometry = installRoomGeometry();+ try {+ const { container } = renderChats();+ await screen.findByText('Main (15551234567)');+ fireEvent.click(await screen.findByText('Alice'));+ const thread = container.querySelector('.room-messages') as HTMLElement;+ await within(thread).findByText('alice extra 39');+ thread.scrollTop = 300; // the reader's spot in Alice's thread+ fireEvent.scroll(thread);++ fireEvent.click(await screen.findByText('Carol'));+ await within(thread).findByText('paged message 119');+ // Alice's thread leaves the cache while the reader is elsewhere, and her first page is slow to come back.+ queryClient!.removeQueries({ queryKey: ['messages', SESSION.id, CHAT.id] });+ let releaseFirstPage!: () => void;+ firstPageGate = new Promise<void>(resolve => {+ releaseFirstPage = resolve;+ });+ fireEvent.click(await screen.findByText('Alice'));+ await waitFor(() => assert.ok(thread.querySelector('.messages-loading')));++ fireEvent.change(screen.getByPlaceholderText('Type a message...'), { target: { value: 'sent while loading' } });+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));+ await waitFor(() => assert.ok(findFetchCall('POST', `/api/sessions/${SESSION.id}/messages/send-text`)));+ await flush();+ releaseFirstPage();+ await within(thread).findByText('sent while loading');+ assert.equal(+ thread.scrollTop,+ thread.scrollHeight - thread.clientHeight,+ 'the message sent while the chat loaded was left below the fold',+ );+ } finally {+ restoreGeometry();+ }+});+// ── Live feed subscription ───────────────────────────────────────────────────const MESSAGE_FEED_EVENTS = [