Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): hold the automatic read while the tab is hidden
Yudhi Armyndharisd42ac55513e8
diff --git a/dashboard/src/pages/Chats.features.test.ts b/dashboard/src/pages/Chats.features.test.tsindex 62907cb0f..6a1e267ea 100644--- a/dashboard/src/pages/Chats.features.test.ts+++ b/dashboard/src/pages/Chats.features.test.ts@@ -7,7 +7,7 @@ import assert from 'node:assert/strict';import { createElement } from 'react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import type { Session, Chat } from '../services/api';-import { resetSocketDouble } from '../test-helpers/socket-io-double.ts';+import { lastSocket, resetSocketDouble } from '../test-helpers/socket-io-double.ts';const SESSION: Session = {id: 'session-1',@@ -1091,6 +1091,85 @@ test('Mark as unread waits for an automatic read already sent, so the unread marassert.equal(readsOf(CHAT.id).length, 1, 'another automatic read followed the unread mark');});+/** Make the document read as hidden (a background tab) or visible again, as the browser does before `visibilitychange`. */+function setTabHidden(hidden: boolean): void {+ if (hidden) {+ Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true });+ Object.defineProperty(document, 'hidden', { value: true, configurable: true });+ } else {+ delete (document as unknown as Record<string, unknown>).visibilityState;+ delete (document as unknown as Record<string, unknown>).hidden;+ }+}++/** A message from Alice, delivered the way the gateway's socket delivers one. */+function receiveFromAlice(id: string, body: string): void {+ rtl.act(() =>+ lastSocket()?.receive('message', {+ type: 'event',+ timestamp: new Date(1_700_002_000_000).toISOString(),+ payload: {+ event: 'message.received',+ sessionId: SESSION.id,+ data: {+ id,+ chatId: CHAT.id,+ from: CHAT.id,+ to: 'me',+ body,+ type: 'text',+ fromMe: false,+ timestamp: 1_700_001_900,+ },+ },+ }),+ );+}++test('a message that reaches the open chat while the tab is hidden is marked read once the tab is visible', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ const { container } = renderPage();+ fireEvent.click(await screen.findByText('Alice'));+ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the room did not open'));+ await waitFor(() => assert.equal(readsOf(CHAT.id).length, 1, 'opening the chat did not mark it read'), {+ timeout: 3_000,+ });+ fetchCalls.length = 0;++ setTabHidden(true);+ try {+ receiveFromAlice('wamid.hidden.1', 'are you there?');+ await screen.findAllByText('are you there?');+ // Past the quiet window the read would have gone out.+ await new Promise(resolve => setTimeout(resolve, 1_000));+ assert.deepEqual(readsOf(CHAT.id), [], 'a hidden tab sent a read receipt');+ } finally {+ setTabHidden(false);+ }+ rtl.act(() => {+ document.dispatchEvent(new window.Event('visibilitychange'));+ });+ await waitFor(() => assert.equal(readsOf(CHAT.id).length, 1, 'the withheld read did not follow'), { timeout: 3_000 });+ assert.ok(!screen.queryByLabelText(/unread message/), 'the open chat was badged');+});++test('a tab that was hidden but sees no message owes no read when it is visible again', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ const { container } = renderPage();+ fireEvent.click(await screen.findByText('Alice'));+ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the room did not open'));+ await waitFor(() => assert.equal(readsOf(CHAT.id).length, 1), { timeout: 3_000 });+ fetchCalls.length = 0;++ setTabHidden(true);+ setTabHidden(false);+ rtl.act(() => {+ document.dispatchEvent(new window.Event('visibilitychange'));+ });+ await new Promise(resolve => setTimeout(resolve, 1_000));+ assert.deepEqual(readsOf(CHAT.id), []);+});+test('on Baileys neither the row nor the room menu offers Clear chat or Delete chat (#1891)', async () => {const { screen, fireEvent, waitFor, within } = rtl;const { container } = renderPage();diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex ab48c2d2b..59bf622e7 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -534,12 +534,19 @@ export function Chats() {// A chat marked unread takes no automatic read until it is opened again, and Mark as unread waits for a// read already sent: otherwise a read queued from the open room lands after the unread and undoes it.// Keyed by session and chat, since a session switch still flushes the previous session's reads.+ // A read due while the tab is hidden is withheld, since nobody has seen what it would acknowledge: it goes out+ // when the tab is visible again (see sendWithheldRead).const [readsInFlight] = useState(() => new Map<string, Promise<void>>());const [keptUnread] = useState(() => new Set<string>());+ const [withheldReads] = useState(() => new Set<string>());const markReadCoalescer = useMemo(() =>createTrailingCoalescer<string>(chatId => {const key = readKey(selectedSessionId, chatId);+ if (document.visibilityState === 'hidden') {+ withheldReads.add(key);+ return;+ }const read = sessionApi.markChatRead(selectedSessionId, chatId).then(() => undefined,err => {@@ -551,7 +558,7 @@ export function Chats() {if (readsInFlight.get(key) === read) readsInFlight.delete(key);});}, MARK_READ_DEBOUNCE_MS),- [selectedSessionId, t, showWarningToast, readsInFlight],+ [selectedSessionId, t, showWarningToast, readsInFlight, withheldReads],);// Flush pending trailing calls on unmount / session switch: the mark-as-read POST is@@ -600,6 +607,20 @@ export function Chats() {},[],);++ // The read withheld from a hidden tab is sent when the tab is visible again, if its chat is still the open one.+ useEffect(() => {+ const sendWithheldRead = () => {+ if (document.visibilityState === 'hidden') return;+ const open = activeChatIdRef.current;+ const withheld = open !== undefined && withheldReads.has(readKey(selectedSessionId, open));+ withheldReads.clear();+ if (withheld) markChatRead(open);+ };+ document.addEventListener('visibilitychange', sendWithheldRead);+ return () => document.removeEventListener('visibilitychange', sendWithheldRead);+ }, [selectedSessionId, markChatRead, withheldReads]);+const handleIncomingMessage = useCallback((event: { sessionId: string; message: Record<string, unknown> }) => {if (event.sessionId !== selectedSessionId) return;