Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): drop media frames queued for a chat that was left
Yudhi Armyndharis215edb66374a
diff --git a/dashboard/src/hooks/useChatScrollPosition.render.test.ts b/dashboard/src/hooks/useChatScrollPosition.render.test.tsindex 77048a923..247c4474e 100644--- a/dashboard/src/hooks/useChatScrollPosition.render.test.ts+++ b/dashboard/src/hooks/useChatScrollPosition.render.test.ts@@ -1586,3 +1586,147 @@ test('a chat left right after a correction for an image above the reader reopensrestore();}});++function queuedMediaFrames() {+ const original = { raf: globalThis.requestAnimationFrame, cancel: globalThis.cancelAnimationFrame };+ let nextId = 0;+ const pending = new Map<number, FrameRequestCallback>();+ const canceled = new Set<number>();+ const ran: number[] = [];+ globalThis.requestAnimationFrame = callback => {+ const id = ++nextId;+ pending.set(id, callback);+ return id;+ };+ globalThis.cancelAnimationFrame = id => {+ pending.delete(id);+ canceled.add(id);+ };+ return {+ pending,+ canceled,+ ran,+ flush() {+ for (const id of [...pending.keys()]) {+ if (!pending.has(id)) continue;+ const callback = pending.get(id)!;+ pending.delete(id);+ assert.equal(canceled.has(id), false);+ ran.push(id);+ callback(0);+ }+ },+ restore() {+ pending.clear();+ globalThis.requestAnimationFrame = original.raf;+ globalThis.cancelAnimationFrame = original.cancel;+ },+ };+}++test('a decode in the next chat is corrected when it arrives before the retired frame', () => {+ rtl.cleanup();+ const frames = queuedMediaFrames();+ const t: Thread = { rows: textRows('a', 46), top: 0 };+ t.rows[10].img = 0;+ const restore = installRows(t);+ try {+ const { rerender, container } = rtl.render(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));+ const el = rtl.screen.getByTestId('thread');+ rtl.fireEvent.scroll(el);+ readerScrollsTo(el, 1210);+ t.rows[10].img = 300;+ hook().onMediaLoad({ currentTarget: container.querySelector('img[data-img="a10"]') });+ assert.equal(frames.pending.size, 1);++ t.rows = textRows('b', 46);+ t.rows[10].img = 0;+ rerender(createElement(RowsProbe, { chatId: 'B', rows: t.rows }));+ rtl.fireEvent.scroll(el);+ readerScrollsTo(el, 1210);+ assert.equal(el.scrollTop, 1210);+ t.rows[10].img = 300;+ hook().onMediaLoad({ currentTarget: container.querySelector('img[data-img="b10"]') });+ frames.flush();+ assert.equal(el.scrollTop, 1510);+ frames.flush();+ assert.equal(el.scrollTop, 1510);+ assert.equal(+ frames.ran.some(id => frames.canceled.has(id)),+ false,+ );+ } finally {+ rtl.cleanup();+ restore();+ frames.restore();+ }+});++test('unmount cancels a pending media frame', () => {+ rtl.cleanup();+ const frames = queuedMediaFrames();+ const t: Thread = { rows: textRows('a', 46), top: 0 };+ t.rows[10].img = 0;+ const restore = installRows(t);+ try {+ const { container, unmount } = rtl.render(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));+ const el = rtl.screen.getByTestId('thread');+ rtl.fireEvent.scroll(el);+ readerScrollsTo(el, 1210);+ t.rows[10].img = 300;+ hook().onMediaLoad({ currentTarget: container.querySelector('img[data-img="a10"]') });+ assert.equal(frames.pending.size, 1);+ unmount();+ assert.equal(frames.pending.size, 0);+ frames.flush();+ assert.equal(frames.ran.length, 0);+ } finally {+ rtl.cleanup();+ restore();+ frames.restore();+ }+});++test('returning to the same chat starts a new media-frame visit', () => {+ rtl.cleanup();+ const frames = queuedMediaFrames();+ const t: Thread = { rows: textRows('a', 46), top: 0 };+ t.rows[10].img = 0;+ const restore = installRows(t);+ try {+ const { rerender, container } = rtl.render(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));+ const el = rtl.screen.getByTestId('thread');+ rtl.fireEvent.scroll(el);+ readerScrollsTo(el, 1210);+ t.rows[10].img = 300;+ hook().onMediaLoad({ currentTarget: container.querySelector('img[data-img="a10"]') });+ const retired = [...frames.pending.keys()][0];+ assert.ok(retired !== undefined);+ const retiredLoad = hook().onMediaLoad;+ const retiredMedia = container.querySelector('img[data-img="a10"]');+ assert.ok(retiredMedia);+ const rowsOfA = t.rows;+ t.rows = textRows('b', 46);+ rerender(createElement(RowsProbe, { chatId: 'B', rows: t.rows }));+ rtl.fireEvent.scroll(el);+ t.rows = rowsOfA.map((row, i) => (i === 10 ? { ...row, img: 0 } : row));+ rerender(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));+ rtl.fireEvent.scroll(el);+ readerScrollsTo(el, 1220);+ assert.equal(retiredMedia.isConnected, false);+ retiredLoad({ currentTarget: retiredMedia });+ assert.equal(frames.pending.size, 0);+ t.rows[10].img = 300;+ hook().onMediaLoad({ currentTarget: container.querySelector('img[data-img="a10"]') });+ assert.ok(frames.canceled.has(retired));+ frames.flush();+ assert.equal(frames.ran.includes(retired), false);+ assert.equal(el.scrollTop, 1520);+ frames.flush();+ assert.equal(el.scrollTop, 1520);+ } finally {+ rtl.cleanup();+ restore();+ frames.restore();+ }+});diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.tsindex d556c36ad..2687be4a8 100644--- a/dashboard/src/hooks/useChatScrollPosition.ts+++ b/dashboard/src/hooks/useChatScrollPosition.ts@@ -217,6 +217,26 @@ export function useChatScrollPosition(const mediaHeights = useRef(new WeakMap<Element, number>());// Media whose load arrived since the last frame, for the reading-position correction in onMediaLoad.const decodedMediaRef = useRef<Element[]>([]);+ const mediaFramesRef = useRef(new Set<number>());+ const mediaVisitRef = useRef(0);++ // Each visit owns its frames and queue, including a return to the same chat.+ const retireMediaFrames = useCallback(() => {+ for (const frame of mediaFramesRef.current) cancelAnimationFrame(frame);+ mediaFramesRef.current.clear();+ decodedMediaRef.current = [];+ mediaVisitRef.current += 1;+ }, []);+ const scheduleMediaFrame = useCallback((apply: () => void) => {+ const visit = mediaVisitRef.current;+ const frame = requestAnimationFrame(() => {+ mediaFramesRef.current.delete(frame);+ if (mediaVisitRef.current === visit) apply();+ });+ mediaFramesRef.current.add(frame);+ }, []);++ useEffect(() => () => retireMediaFrames(), [retireMediaFrames]);const writeScrollTop = useCallback((el: HTMLDivElement, top: number) => {el.scrollTop = top;@@ -325,7 +345,10 @@ export function useChatScrollPosition(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;+ if (next !== prevChatIdRef.current) {+ awaitingOlderPageRef.current = false;+ retireMediaFrames();+ }const decision = decideRestoreTarget(next, isLoaded, next !== null ? scrollMap.current.get(next)?.top : undefined);// A message the reader sent while this chat loaded opens it at that message, the way a send in a loaded chat@@ -350,7 +373,7 @@ export function useChatScrollPosition(prevChatIdRef.current = next;loadedRef.current = isLoaded;- }, [activeChatId, isLoaded, followBottom, pinToBottom, writeScrollTop]);+ }, [activeChatId, isLoaded, followBottom, pinToBottom, writeScrollTop, retireMediaFrames]);const onOlderMessagesRequested = useCallback(() => {const el = containerRef.current;@@ -493,11 +516,14 @@ export function useChatScrollPosition(// write to a different thread, and save it under that thread's id. prevChatIdRef holds whichever chat is// actually on screen, set by the restore effect above.const onScreen = () => prevChatIdRef.current === activeChatId;+ if (!onScreen()) return;+ const media = event?.currentTarget ?? null;+ if (media && (!containerRef.current?.contains(media) || !mediaHeights.current.has(media))) return;const pending = pendingRestoreRef.current;if (pending !== null) {- requestAnimationFrame(() => {+ scheduleMediaFrame(() => {const cur = containerRef.current;- if (!cur || !onScreen() || pendingRestoreRef.current === null) return;+ if (!cur || !onScreen() || pendingRestoreRef.current !== pending) return;writeScrollTop(cur, savedSpotTop(cur, pending));// What grew above the spot is absorbed by this write: a page still out is held from where it put the reader.if (awaitingOlderPageRef.current) onOlderMessagesRequested();@@ -505,7 +531,7 @@ export function useChatScrollPosition(return;}if (pinnedRef.current) {- requestAnimationFrame(() => {+ scheduleMediaFrame(() => {const cur = containerRef.current;if (cur && onScreen() && pinnedRef.current) followBottom(cur);});@@ -513,20 +539,19 @@ export function useChatScrollPosition(}if (!containerRef.current) return;// Which element grew, and by how much, decides whether the reader moved at all.- const media = event?.currentTarget ?? null;- if (!media || !mediaHeights.current.has(media)) return;+ if (!media) return;// Measured in the frame, top to bottom, each after the corrections above it: read when its load event fires,// an element can sit below another that grew in the same frame and was not corrected yet, and then reads as// below the reader by that growth.const decoded = decodedMediaRef.current;decoded.push(media);if (decoded.length > 1) return;- requestAnimationFrame(() => {+ scheduleMediaFrame(() => {if (onScreen()) applyMediaGrowth();else decoded.length = 0;});},- [activeChatId, applyMediaGrowth, followBottom, onOlderMessagesRequested, writeScrollTop],+ [activeChatId, applyMediaGrowth, followBottom, onOlderMessagesRequested, writeScrollTop, scheduleMediaFrame],);return { containerRef, onMessageAppended, onMediaLoad, measureMedia, onOlderMessagesRequested };