Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): keep chat actions correct under StrictMode and auto-read

Rezk Jörg Sebening2c462c120444
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2d423e53b..0933bd4d6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,7 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add the opt-in `message.receipt` event for per-recipient group and status receipts on Baileys (#1748).
- Add All, Unread, 1:1, Groups and Unknown quick filters to the dashboard chat list, where Unread includes chats marked unread and Unknown lists 1:1 chats whose contact is not saved.
- Add a New chat panel to the dashboard Chats page for operator keys that opens a chat with a saved contact or a typed international number once the gateway confirms the number is on WhatsApp, and on Baileys creates a group from a name and picked contacts or numbers.
-- Add a menu to every dashboard chat row and to the open chat's header that pins, mutes, archives, marks unread, clears or deletes a chat, saves, renames or blocks its contact, and leaves a group, asking first before an action that cannot be undone; the header's menu also copies the chat id and closes the chat.
+- Add a menu to every dashboard chat row and to the open chat's header that pins, mutes, archives, marks unread, clears or deletes a chat (on whatsapp-web.js only for now, see #1891), saves, renames or blocks its contact, and leaves a group, asking first before an action that cannot be undone; the header's menu also copies the chat id and closes the chat.
- Add an Archived view to the dashboard chat list; archived chats leave the main list, and pinned chats lead it.
- Add a group info dialog to the dashboard Chats page that edits a group's name, picture and description and adds, removes, promotes and demotes its participants when the account administers the group.
diff --git a/dashboard/src/components/chats/NewChatPanel.tsx b/dashboard/src/components/chats/NewChatPanel.tsx
index 0de73a9e5..68617690a 100644
--- a/dashboard/src/components/chats/NewChatPanel.tsx
+++ b/dashboard/src/components/chats/NewChatPanel.tsx
@@ -75,14 +75,15 @@ function NewChatPanel({ sessionId, onOpenChat, onClose }: NewChatPanelProps) {
const [participants, setParticipants] = useState<Participant[]>([]);
const [creating, setCreating] = useState(false);
// A lookup or a group creation can answer after the panel was closed (Back, or a session switch, which
- // unmounts it). Its result then belongs to nothing on screen and is dropped.
+ // unmounts it). Its result then belongs to nothing on screen and is dropped. Setup sets the flag again:
+ // StrictMode replays setup after a cleanup on a panel that stays mounted.
const openRef = useRef(true);
- useEffect(
- () => () => {
+ useEffect(() => {
+ openRef.current = true;
+ return () => {
openRef.current = false;
- },
- [],
- );
+ };
+ }, []);
const contactsQuery = useQuery({
queryKey: ['contacts', sessionId],
diff --git a/dashboard/src/pages/Chats.features.test.ts b/dashboard/src/pages/Chats.features.test.ts
index 431921035..6948b2214 100644
--- a/dashboard/src/pages/Chats.features.test.ts
+++ b/dashboard/src/pages/Chats.features.test.ts
@@ -171,7 +171,7 @@ function installFetchStub(): void {
return Promise.resolve(jsonResponse({ messages: [], total: 0 }));
}
if (method === 'GET' && /\/messages\/[^/]+\/history/.test(path)) return Promise.resolve(jsonResponse([]));
- if (method === 'POST' && path === `${base}/chats/read`) return Promise.resolve(jsonResponse({ success: true }));
+ if (method === 'POST' && path === `${base}/chats/read`) return gated('read', () => jsonResponse({ success: true }));
if (method === 'POST' && path === `${base}/groups`) {
return gated('createGroup', () => jsonResponse({ id: GROUP_ID, name: (body as { name: string }).name }, 201));
}
@@ -223,7 +223,8 @@ afterEach(async () => {
window.sessionStorage.setItem('openwa_engine_type', 'baileys');
});
-function renderPage(): ReturnType<RTL['render']> {
+/** Renders the page; `reactStrictMode` replays effect setup and cleanup as `main.tsx` does in development. */
+function renderPage({ reactStrictMode = false } = {}): ReturnType<RTL['render']> {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });
queryClients.push(queryClient);
return rtl.render(
@@ -232,6 +233,7 @@ function renderPage(): ReturnType<RTL['render']> {
{ client: queryClient },
createElement(RoleProvider, null, createElement(ToastProvider, null, createElement(Chats))),
),
+ { reactStrictMode },
);
}
@@ -252,51 +254,55 @@ test('a quick filter that matches no chat says so instead of claiming the accoun
assert.ok(!screen.queryByText('Alice'), 'the filter left a 1:1 chat in the groups list');
});
-test('a typed number is checked with the gateway and opens a chat under the id it resolves to', async () => {
- const { screen, fireEvent, waitFor, within } = rtl;
- const { container } = renderPage();
- await screen.findByText('Alice');
- fireEvent.click(screen.getByRole('button', { name: 'New chat' }));
- fireEvent.change(screen.getByLabelText('Search name or number with country code'), {
- target: { value: TYPED_NUMBER },
+for (const reactStrictMode of [false, true]) {
+ test(`a typed number is checked with the gateway and opens a chat under the id it resolves to${reactStrictMode ? ' (StrictMode)' : ''}`, async () => {
+ const { screen, fireEvent, waitFor, within } = rtl;
+ const { container } = renderPage({ reactStrictMode });
+ await screen.findByText('Alice');
+ fireEvent.click(screen.getByRole('button', { name: 'New chat' }));
+ fireEvent.change(screen.getByLabelText('Search name or number with country code'), {
+ target: { value: TYPED_NUMBER },
+ });
+ fireEvent.click(screen.getByRole('button', { name: /^Start chat with/ }));
+
+ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the new chat did not open'));
+ assert.ok(
+ fetchCalls.some(c => c.method === 'GET' && c.path === `/api/sessions/${SESSION.id}/contacts/check/15550009999`),
+ 'the number was not checked with the gateway',
+ );
+ await within(container.querySelector('.room-header') as HTMLElement).findByText('15550009999');
+ assert.ok(!container.querySelector('.new-chat-panel'), 'the panel stayed open over the list');
});
- fireEvent.click(screen.getByRole('button', { name: /^Start chat with/ }));
-
- await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the new chat did not open'));
- assert.ok(
- fetchCalls.some(c => c.method === 'GET' && c.path === `/api/sessions/${SESSION.id}/contacts/check/15550009999`),
- 'the number was not checked with the gateway',
- );
- await within(container.querySelector('.room-header') as HTMLElement).findByText('15550009999');
- assert.ok(!container.querySelector('.new-chat-panel'), 'the panel stayed open over the list');
-});
-
-test('a group is created with the picked contacts on Baileys, and whatsapp-web.js is not offered one', async () => {
- const { screen, fireEvent, waitFor, within } = rtl;
- const { container } = renderPage();
- await screen.findByText('Alice');
- fireEvent.click(screen.getByRole('button', { name: 'New chat' }));
- fireEvent.click(screen.getByRole('button', { name: 'New group' }));
- fireEvent.change(screen.getByLabelText('Group name'), { target: { value: 'Team' } });
- fireEvent.click(await screen.findByRole('button', { name: /Bob/ }));
- fireEvent.click(screen.getByRole('button', { name: 'Create group' }));
-
- await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the new group did not open'));
- const create = fetchCalls.find(c => c.method === 'POST' && c.path === `/api/sessions/${SESSION.id}/groups`);
- assert.deepEqual(create?.body, { name: 'Team', participants: [CONTACT.id] });
- await within(container.querySelector('.room-header') as HTMLElement).findByText('Team');
- rtl.cleanup();
+}
- window.sessionStorage.setItem('openwa_engine_type', 'whatsapp-web.js');
- renderPage();
- await screen.findByText('Alice');
- fireEvent.click(screen.getByRole('button', { name: 'New chat' }));
- await screen.findByText('Bob');
- assert.ok(
- !screen.queryByRole('button', { name: 'New group' }),
- 'whatsapp-web.js, which answers 501, offered a group',
- );
-});
+for (const reactStrictMode of [false, true]) {
+ test(`a group is created with the picked contacts on Baileys, and whatsapp-web.js is not offered one${reactStrictMode ? ' (StrictMode)' : ''}`, async () => {
+ const { screen, fireEvent, waitFor, within } = rtl;
+ const { container } = renderPage({ reactStrictMode });
+ await screen.findByText('Alice');
+ fireEvent.click(screen.getByRole('button', { name: 'New chat' }));
+ fireEvent.click(screen.getByRole('button', { name: 'New group' }));
+ fireEvent.change(screen.getByLabelText('Group name'), { target: { value: 'Team' } });
+ fireEvent.click(await screen.findByRole('button', { name: /Bob/ }));
+ fireEvent.click(screen.getByRole('button', { name: 'Create group' }));
+
+ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the new group did not open'));
+ const create = fetchCalls.find(c => c.method === 'POST' && c.path === `/api/sessions/${SESSION.id}/groups`);
+ assert.deepEqual(create?.body, { name: 'Team', participants: [CONTACT.id] });
+ await within(container.querySelector('.room-header') as HTMLElement).findByText('Team');
+ rtl.cleanup();
+
+ window.sessionStorage.setItem('openwa_engine_type', 'whatsapp-web.js');
+ renderPage({ reactStrictMode });
+ await screen.findByText('Alice');
+ fireEvent.click(screen.getByRole('button', { name: 'New chat' }));
+ await screen.findByText('Bob');
+ assert.ok(
+ !screen.queryByRole('button', { name: 'New group' }),
+ 'whatsapp-web.js, which answers 501, offered a group',
+ );
+ });
+}
test('a group row offers its actions, and marking it unread badges the row', async () => {
const { screen, fireEvent, waitFor } = rtl;
@@ -397,8 +403,9 @@ test('a member who is no admin sees the group read-only, and a viewer key gets n
assert.ok((within(dialog).getByRole('button', { name: 'Save changes' }) as HTMLButtonElement).disabled);
});
-test('a 1:1 row clears its chat and deletes it, each only after its own confirmation', async () => {
+test('a 1:1 row clears its chat and deletes it on whatsapp-web.js, each only after its own confirmation', async () => {
const { screen, fireEvent, waitFor, within } = rtl;
+ window.sessionStorage.setItem('openwa_engine_type', 'whatsapp-web.js');
renderPage();
await screen.findByText('Alice');
const chatPath = `/api/sessions/${SESSION.id}/chats`;
@@ -636,6 +643,7 @@ test("a pin that answers after a switch does not pin the other session's chat wi
test('a clear or delete the engine declines keeps the chat and its dialog, and says it failed', async () => {
const { screen, fireEvent, within } = rtl;
declineWrites = true;
+ window.sessionStorage.setItem('openwa_engine_type', 'whatsapp-web.js');
renderPage();
await screen.findByText('Alice');
@@ -693,3 +701,71 @@ test('a chat keyed by a privacy id offers Save contact disabled, with the reason
assert.ok(!screen.queryByRole('dialog'), 'the save dialog opened for a @lid chat');
assert.ok(!fetchCalls.some(c => c.method === 'PUT' && c.path.includes('/contacts/')), 'a @lid id was sent');
});
+
+// ── Mark as unread against the automatic read the open room queues (MARK_READ_DEBOUNCE_MS later). ──
+
+const readsOf = (chatId: string) =>
+ fetchCalls.filter(
+ c => c.path === `/api/sessions/${SESSION.id}/chats/read` && (c.body as { chatId?: string })?.chatId === chatId,
+ );
+const unreadIndex = (chatId: string) =>
+ fetchCalls.findIndex(
+ c => c.path === `/api/sessions/${SESSION.id}/chats/unread` && (c.body as { chatId?: string })?.chatId === chatId,
+ );
+
+test("Mark as unread drops the chat's queued automatic read, and another chat's queued read still goes out", async () => {
+ const { screen, fireEvent, waitFor } = rtl;
+ listGroup = true;
+ const { container } = renderPage();
+ fireEvent.click(await screen.findByText('Team'));
+ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the group did not open'));
+ // Both reads are now queued: the group's from its opening, Alice's from hers.
+ fireEvent.click(screen.getByText('Alice'));
+ pickRowAction('Alice', 'Mark as unread');
+
+ await waitFor(() => assert.equal(readsOf(GROUP.id).length, 1, "the other chat's queued read was dropped"), {
+ timeout: 3_000,
+ });
+ await waitFor(() => assert.ok(unreadIndex(CHAT.id) >= 0, 'the unread mark was not sent'));
+ await settle();
+ assert.deepEqual(readsOf(CHAT.id), [], 'the queued read went out and undid the unread mark');
+});
+
+test('Mark as unread waits for an automatic read already sent, so the unread mark is the last request', async () => {
+ const { screen, fireEvent, waitFor } = rtl;
+ const release = hold('read');
+ renderPage();
+ fireEvent.click(await screen.findByText('Alice'));
+ await waitFor(() => assert.equal(readsOf(CHAT.id).length, 1, 'the automatic read was not sent'), {
+ timeout: 3_000,
+ });
+
+ pickRowAction('Alice', 'Mark as unread');
+ await settle();
+ assert.equal(unreadIndex(CHAT.id), -1, 'the unread mark went out while the read was still in flight');
+
+ release();
+ await waitFor(() => assert.ok(unreadIndex(CHAT.id) >= 0, 'the unread mark was not sent'));
+ const readIndex = fetchCalls.indexOf(readsOf(CHAT.id)[0]);
+ assert.ok(readIndex < unreadIndex(CHAT.id), 'the read was not ordered before the unread mark');
+ assert.equal(readsOf(CHAT.id).length, 1, 'another automatic read followed the unread mark');
+});
+
+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();
+ fireEvent.click(await screen.findByText('Alice'));
+ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the room did not open'));
+
+ fireEvent.click(screen.getByRole('button', { name: 'Actions for Alice' }));
+ assert.ok(screen.getByRole('button', { name: 'Archive chat' }), 'the row menu did not open');
+ assert.ok(!screen.queryByRole('button', { name: 'Clear chat' }), 'the row menu offered Clear chat');
+ assert.ok(!screen.queryByRole('button', { name: 'Delete chat' }), 'the row menu offered Delete chat');
+ fireEvent.keyDown(document, { key: 'Escape' });
+
+ fireEvent.click(container.querySelector('.room-menu-trigger') as HTMLElement);
+ const menu = container.querySelector('.room-menu-popover') as HTMLElement;
+ assert.ok(within(menu).getByRole('button', { name: 'Copy chat ID' }), 'the room menu did not open');
+ assert.ok(!within(menu).queryByRole('button', { name: 'Clear chat' }), 'the room menu offered Clear chat');
+ assert.ok(!within(menu).queryByRole('button', { name: 'Delete chat' }), 'the room menu offered Delete chat');
+});
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 717b248c4..b592707a5 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -88,6 +88,7 @@ import './Chats.css';
// Quiet window for coalescing mark-as-read RPCs (see markReadCoalescer below).
const MARK_READ_DEBOUNCE_MS = 750;
+const readKey = (sessionId: string, chatId: string) => `${sessionId}\u0000${chatId}`;
// mergeDeliveryStatus (forward-only delivery-tick merge) is shared with mergeOrAppend in utils/chatMessages
// so the WS append path and the ack path apply the exact same rule.
@@ -226,6 +227,9 @@ export function Chats() {
// both, so the query is gated off entirely (never fired) rather than left to fail per-request.
// The engine comes from the sign-in validate response, which every role can read.
const channelsSupported = engineType === 'whatsapp-web.js';
+ // On Baileys the phone can ignore a clear or delete the gateway reports as done, and the gateway then drops
+ // its stored copy of the messages (#1891). Until that is fixed both are offered on whatsapp-web.js only.
+ const canClearOrDelete = canWrite && engineType === 'whatsapp-web.js';
const channelsQuery = useQuery({
queryKey: ['channels', selectedSessionId],
queryFn: () => sessionApi.getSubscribedChannels(selectedSessionId!),
@@ -484,14 +488,27 @@ export function Chats() {
// Coalesce mark-as-read RPCs per chat: every incoming message in the visible chat raises a
// read event, and a per-event POST sprays the gateway into 429s. One trailing call per chat
// after a quiet window carries the same effect.
+ // 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.
+ const [readsInFlight] = useState(() => new Map<string, Promise<void>>());
+ const [keptUnread] = useState(() => new Set<string>());
const markReadCoalescer = useMemo(
() =>
createTrailingCoalescer<string>(chatId => {
- void sessionApi.markChatRead(selectedSessionId, chatId).catch(err => {
- showWarningToast(t('chats.errors.markRead'), err instanceof Error ? err.message : undefined);
+ const key = readKey(selectedSessionId, chatId);
+ const read = sessionApi.markChatRead(selectedSessionId, chatId).then(
+ () => undefined,
+ err => {
+ showWarningToast(t('chats.errors.markRead'), err instanceof Error ? err.message : undefined);
+ },
+ );
+ readsInFlight.set(key, read);
+ void read.finally(() => {
+ if (readsInFlight.get(key) === read) readsInFlight.delete(key);
});
}, MARK_READ_DEBOUNCE_MS),
- [selectedSessionId, t, showWarningToast],
+ [selectedSessionId, t, showWarningToast, readsInFlight],
);
// Flush pending trailing calls on unmount / session switch: the mark-as-read POST is
@@ -514,9 +531,10 @@ export function Chats() {
// account's and nothing is marked read.
const markChatRead = useCallback(
(chatId: string) => {
+ if (keptUnread.has(readKey(selectedSessionId, chatId))) return;
if (canWrite && listedSessionRef.current === selectedSessionId) markReadCoalescer.call(chatId);
},
- [markReadCoalescer, canWrite, selectedSessionId],
+ [markReadCoalescer, canWrite, selectedSessionId, keptUnread],
);
// 3. WebSocket integration for real-time messages
@@ -924,6 +942,8 @@ export function Chats() {
// 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.
+ keptUnread.delete(readKey(selectedSessionId, activeChat.id));
markChatRead(activeChat.id);
// A read-only key sends no mark-as-read, so the chat stays unread on the gateway; clearing the
// badge here would only have the next chat-list load bring it back.
@@ -1136,13 +1156,18 @@ export function Chats() {
const handleMarkUnread = async (chat: Chat) => {
const sessionId = selectedSessionId;
+ const key = readKey(sessionId, chat.id);
+ keptUnread.add(key);
+ markReadCoalescer.drop(chat.id);
try {
+ await readsInFlight.get(key);
expectSuccess(await sessionApi.markChatUnread(sessionId, chat.id));
if (!stillOn(sessionId)) return;
// A negative count is how the list shows a chat marked unread (a badge with no number).
patchChat(sessionId, chat.id, { unreadCount: -1 });
if (activeChatIdRef.current === chat.id) setActiveChat(null);
} catch (err) {
+ keptUnread.delete(key);
failWith('chats.rowActions.markUnreadFailed')(err);
}
};
@@ -1254,8 +1279,8 @@ export function Chats() {
onToggleBlock: canWrite
? chat => (isBlocked(chat) ? void handleUnblock(chat) : setConfirmAction({ kind: 'block', chat }))
: undefined,
- onClear: canWrite ? chat => setConfirmAction({ kind: 'clear', chat }) : undefined,
- onDelete: canWrite ? chat => setConfirmAction({ kind: 'delete', chat }) : undefined,
+ onClear: canClearOrDelete ? chat => setConfirmAction({ kind: 'clear', chat }) : undefined,
+ onDelete: canClearOrDelete ? chat => setConfirmAction({ kind: 'delete', chat }) : undefined,
isBlocked,
};
diff --git a/dashboard/src/utils/trailingCoalescer.test.ts b/dashboard/src/utils/trailingCoalescer.test.ts
index 80eac8157..eea2d24b9 100644
--- a/dashboard/src/utils/trailingCoalescer.test.ts
+++ b/dashboard/src/utils/trailingCoalescer.test.ts
@@ -61,6 +61,20 @@ test('cancel() drops pending calls so nothing fires late', t => {
assert.deepEqual(sent, []);
});
+test('drop(key) drops that key only, so the other keys still fire', t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sent: string[] = [];
+ const coalescer = createTrailingCoalescer<string>(key => sent.push(key), 750);
+
+ coalescer.call('chat-A');
+ coalescer.call('chat-B');
+ coalescer.drop('chat-A');
+ coalescer.drop('chat-C');
+
+ t.mock.timers.tick(10_000);
+ assert.deepEqual(sent, ['chat-B']);
+});
+
test('flush() fires every pending key immediately (unmount/navigation does not lose the call)', t => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const sent: string[] = [];
diff --git a/dashboard/src/utils/trailingCoalescer.ts b/dashboard/src/utils/trailingCoalescer.ts
index e15265d0b..9190d610a 100644
--- a/dashboard/src/utils/trailingCoalescer.ts
+++ b/dashboard/src/utils/trailingCoalescer.ts
@@ -5,12 +5,13 @@
// event, and a per-event POST sprays the gateway into 429s. Keys are independent (each chat
// gets its own quiet window). `flush()` fires every pending key immediately — used on
// unmount/navigation so a queued mark-as-read isn't lost when the user leaves mid-window —
-// while `cancel()` drops pending calls without firing them.
+// while `cancel()` drops pending calls without firing them, and `drop(key)` drops one key's.
export interface TrailingCoalescer<K> {
call(key: K): void;
flush(): void;
cancel(): void;
+ drop(key: K): void;
}
export function createTrailingCoalescer<K>(send: (key: K) => void, delayMs: number): TrailingCoalescer<K> {
@@ -37,5 +38,9 @@ export function createTrailingCoalescer<K>(send: (key: K) => void, delayMs: numb
for (const timer of timers.values()) clearTimeout(timer);
timers.clear();
},
+ drop(key: K) {
+ clearTimeout(timers.get(key));
+ timers.delete(key);
+ },
};
}
diff --git a/docs/17-dashboard-design.md b/docs/17-dashboard-design.md
index 7413d3f2d..1037c3e48 100644
--- a/docs/17-dashboard-design.md
+++ b/docs/17-dashboard-design.md
@@ -111,8 +111,9 @@ mounted for any admin key.
/chats → Chats (Chats / Channels / Status tabs, quick filters and an Archived view on
Chats; chat list + message thread live via WebSocket; thread pages older
history in on scroll-up; per-chat menu (pin, mute, archive, mark unread,
- block, clear, delete, leave group) [operator]; group info dialog; new chat /
- new group [operator]; read-only channel feed on whatsapp-web.js)
+ block, leave group; clear and delete on whatsapp-web.js only) [operator];
+ group info dialog; new chat / new group [operator]; read-only channel feed
+ on whatsapp-web.js)
/webhooks → Webhooks (per-session webhook endpoints)
/templates → Message Templates
/message-tester → Message Tester (ad-hoc send-* + check-number)