Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): keep reading positions per session

Yudhi Armyndharis6443654ec47b
diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.ts
index 969946b01..9c1b4ed9d 100644
--- a/dashboard/src/hooks/useChatScrollPosition.ts
+++ b/dashboard/src/hooks/useChatScrollPosition.ts
@@ -69,7 +69,8 @@ export function decideRestoreTarget(
* div in Chats.tsx). The Map of saved positions lives in a ref so it doesn't
* trigger renders and is garbage-collected when the host component unmounts. A chat the
* reader left at the bottom has no entry (it reopens at its newest message), however
- * much arrived after their last scroll.
+ * much arrived after their last scroll. The key names a thread, not just a chat: the
+ * caller puts the session into it, since one chat id can have a thread in two sessions.
*/
/** Distance from the bottom (px) within which the user still counts as "at the bottom". */
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index 12d326e2b..cb349704b 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -3216,3 +3216,92 @@ test('a live sidebar row survives movement outside a paginated reconnect snapsho
assert.equal(rtl.screen.getAllByText('Updated during paging').length, 1);
assert.ok(rtl.screen.queryByLabelText('3 unread messages'));
});
+
+// ── Reading position of a thread ─────────────────────────────────────────────
+
+const ROOM_HEIGHT = 600;
+
+/**
+ * Scroll geometry for every `.room-messages` the page mounts, clamped to the content as a browser clamps it. The
+ * room unmounts when a session switch closes its chat, so a shim on one element (makeScrollable) would arrive
+ * after the restore it is meant to see. Content height is the bubbles, as in makeScrollable.
+ */
+function installRoomGeometry(): () => void {
+ const proto = window.HTMLDivElement.prototype;
+ const inherited = Object.getOwnPropertyDescriptors(window.Element.prototype);
+ const tops = new WeakMap<Element, number>();
+ const isRoom = (el: Element): boolean => el.classList.contains('room-messages');
+ const contentHeight = (el: Element): number => el.querySelectorAll('.message-bubble').length * BUBBLE_PX;
+ const maxTop = (el: Element): number => Math.max(0, contentHeight(el) - ROOM_HEIGHT);
+ Object.defineProperties(proto, {
+ scrollHeight: {
+ configurable: true,
+ get(this: Element) {
+ return isRoom(this) ? contentHeight(this) : inherited.scrollHeight.get!.call(this);
+ },
+ },
+ clientHeight: {
+ configurable: true,
+ get(this: Element) {
+ return isRoom(this) ? ROOM_HEIGHT : inherited.clientHeight.get!.call(this);
+ },
+ },
+ scrollTop: {
+ configurable: true,
+ get(this: Element) {
+ return isRoom(this) ? Math.min(tops.get(this) ?? 0, maxTop(this)) : inherited.scrollTop.get!.call(this);
+ },
+ set(this: Element, value: number) {
+ if (isRoom(this)) tops.set(this, Math.max(0, Math.min(value, maxTop(this))));
+ else inherited.scrollTop.set!.call(this, value);
+ },
+ },
+ });
+ return () => {
+ for (const key of ['scrollHeight', 'clientHeight', 'scrollTop'] as const) {
+ delete (proto as unknown as Record<string, unknown>)[key];
+ }
+ };
+}
+
+test('a chat opened in another session starts at its newest message, not at the offset left in the first', async () => {
+ const { screen, fireEvent, within } = rtl;
+ twoSessions = true;
+ // Session 2 lists Carol too, a contact both accounts share.
+ chatsResponder = sessionId =>
+ Promise.resolve(
+ jsonResponse(sessionId === SESSION.id ? [CHAT, CHAT_2] : [CHAT, { ...CHAT_2, lastMessage: 'carol on two' }]),
+ );
+ const restoreGeometry = installRoomGeometry();
+ try {
+ const { container } = renderChats();
+ const thread = await openPagedChat(container);
+ assert.equal(thread.scrollTop, thread.scrollHeight - thread.clientHeight, 'a first visit did not open at the end');
+
+ thread.scrollTop = 900; // the reader goes back through Carol's history in the first session
+ fireEvent.scroll(thread);
+
+ const selector = container.querySelector('select.session-selector') as HTMLSelectElement;
+ fireEvent.change(selector, { target: { value: SESSION_2.id } });
+ await screen.findByText('carol on two');
+ fireEvent.click(screen.getByText('Carol'));
+ const second = container.querySelector('.room-messages') as HTMLElement;
+ await within(second).findByText('paged message 119');
+ assert.equal(
+ second.scrollTop,
+ second.scrollHeight - second.clientHeight,
+ "Carol opened in the second session at the offset left in the first session's thread",
+ );
+
+ // The first session's own position is still there when the reader comes back to it.
+ fireEvent.change(selector, { target: { value: SESSION.id } });
+ await screen.findByText('hello from carol');
+ fireEvent.click(screen.getByText('Carol'));
+ const back = container.querySelector('.room-messages') as HTMLElement;
+ await within(back).findByText('paged message 119');
+ assert.equal(back.scrollTop, 900, "the first session's position was lost");
+ } finally {
+ restoreGeometry();
+ twoSessions = false;
+ }
+});
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 9c2054f87..d61132c02 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -343,13 +343,19 @@ export function Chats() {
// chat has any message (doesn't toggle per append) and covers both the
// first-fetch resolution and a WS-driven first message on a previously-empty
// chat. `loadingMessages` alone would miss the latter case.
+ // The position is kept per thread, so the key carries the session: a group both numbers belong to has one chat
+ // id and two threads, and the offset read in one is not a place in the other.
const {
containerRef: messagesContainerRef,
onMessageAppended,
onMediaLoad,
measureMedia,
onOlderMessagesRequested,
- } = useChatScrollPosition(activeChat?.id ?? null, messages.length > 0, loadingOlderMessages);
+ } = useChatScrollPosition(
+ activeChat ? `${selectedSessionId}:${activeChat.id}` : null,
+ messages.length > 0,
+ loadingOlderMessages,
+ );
const handleLoadOlderMessages = useCallback(() => {
onOlderMessagesRequested();
@@ -1104,9 +1110,9 @@ export function Chats() {
// Side effects when the active chat changes: mark-as-read on the gateway + clear sidebar unread badge.
// The message-history fetch is driven by useChatMessages; scroll restoration is driven by
- // useChatScrollPosition (both keyed off activeChat?.id). Deliberately keying off `activeChat?.id`
- // (not the whole object) so a sidebar reshuffle that mutates the activeChat instance doesn't re-fire
- // the mark-as-read RPC for the same chat.
+ // useChatScrollPosition (both keyed off activeChat?.id, the latter with the session too). Deliberately keying
+ // off `activeChat?.id` (not the whole object) so a sidebar reshuffle that mutates the activeChat instance
+ // doesn't re-fire the mark-as-read RPC for the same chat.
useEffect(() => {
if (!activeChat) return;
// Opening a chat is what reads it again after Mark as unread.