Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): refuse a search hit in a session that is not ready
Yudhi Armyndharis4dabcd47db8b
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex d06fc1a62..8543b586e 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -199,7 +199,8 @@"react": "فشل التفاعل مع الرسالة","delete": "فشل حذف الرسالة","clickButton": "فشل النقر على الزر",- "fileTooLarge": "الملف كبير جدًا (الحد الأقصى 18 ميغابايت)"+ "fileTooLarge": "الملف كبير جدًا (الحد الأقصى 18 ميغابايت)",+ "searchHitSessionNotReady": "جلسة هذه الرسالة غير متصلة"},"loadMessagesError": "تعذّر تحميل الرسائل. تحقّق من سجلّات الخادم.","messageStatus": {diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex 50ab09c7c..416bf1371 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -186,7 +186,8 @@"react": "Reaktion auf die Nachricht fehlgeschlagen","delete": "Nachricht konnte nicht gelöscht werden","clickButton": "Schaltfläche konnte nicht angeklickt werden",- "fileTooLarge": "Die Datei ist zu groß (max. 18 MB)"+ "fileTooLarge": "Die Datei ist zu groß (max. 18 MB)",+ "searchHitSessionNotReady": "Die Sitzung dieser Nachricht ist nicht verbunden"},"loadMessagesError": "Nachrichten konnten nicht geladen werden. Prüfe die Serverprotokolle.","messageStatus": {diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex c02fd5abf..08cb07641 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -186,7 +186,8 @@"react": "Failed to react to message","delete": "Failed to delete message","clickButton": "Failed to click button",- "fileTooLarge": "File is too large (max 18 MB)"+ "fileTooLarge": "File is too large (max 18 MB)",+ "searchHitSessionNotReady": "The session of this message is not connected"},"loadMessagesError": "Couldn't load messages. Check the server logs.","messageStatus": {diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex ac17efde4..9ab715f15 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -189,7 +189,8 @@"react": "Error al reaccionar al mensaje","delete": "Error al eliminar el mensaje","clickButton": "Error al pulsar el botón",- "fileTooLarge": "El archivo es demasiado grande (máx. 18 MB)"+ "fileTooLarge": "El archivo es demasiado grande (máx. 18 MB)",+ "searchHitSessionNotReady": "La sesión de este mensaje no está conectada"},"loadMessagesError": "No se pudieron cargar los mensajes. Revisa los registros del servidor.","messageStatus": {diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex 064cac7e0..2f42866f4 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -189,7 +189,8 @@"react": "Échec de la réaction au message","delete": "Échec de la suppression du message","clickButton": "Échec du clic sur le bouton",- "fileTooLarge": "Le fichier est trop volumineux (max 18 Mo)"+ "fileTooLarge": "Le fichier est trop volumineux (max 18 Mo)",+ "searchHitSessionNotReady": "La session de ce message n'est pas connectée"},"loadMessagesError": "Impossible de charger les messages. Vérifiez les journaux du serveur.","messageStatus": {diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex f7980b3a3..7c9f3d7fb 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -193,7 +193,8 @@"react": "התגובה להודעה נכשלה","delete": "מחיקת ההודעה נכשלה","clickButton": "לחיצה על הכפתור נכשלה",- "fileTooLarge": "הקובץ גדול מדי (מקסימום 18 MB)"+ "fileTooLarge": "הקובץ גדול מדי (מקסימום 18 MB)",+ "searchHitSessionNotReady": "הסשן של הודעה זו אינו מחובר"},"loadMessagesError": "לא ניתן לטעון את ההודעות. בדקו את יומני השרת.","messageStatus": {diff --git a/dashboard/src/i18n/locales/hi.json b/dashboard/src/i18n/locales/hi.jsonindex 5363930e3..a0df40f49 100644--- a/dashboard/src/i18n/locales/hi.json+++ b/dashboard/src/i18n/locales/hi.json@@ -186,7 +186,8 @@"react": "संदेश पर प्रतिक्रिया देने में विफल","delete": "संदेश हटाने में विफल","clickButton": "बटन पर क्लिक करने में विफल",- "fileTooLarge": "फ़ाइल बहुत बड़ी है (अधिकतम 18 MB)"+ "fileTooLarge": "फ़ाइल बहुत बड़ी है (अधिकतम 18 MB)",+ "searchHitSessionNotReady": "इस संदेश का सत्र कनेक्ट नहीं है"},"loadMessagesError": "संदेश लोड नहीं किए जा सके। सर्वर लॉग्स की जाँच करें।","messageStatus": {diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 0cd47df67..101e5b175 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -189,7 +189,8 @@"react": "Impossibile reagire al messaggio","delete": "Impossibile eliminare il messaggio","clickButton": "Impossibile cliccare il pulsante",- "fileTooLarge": "Il file è troppo grande (max 18 MB)"+ "fileTooLarge": "Il file è troppo grande (max 18 MB)",+ "searchHitSessionNotReady": "La sessione di questo messaggio non è connessa"},"loadMessagesError": "Impossibile caricare i messaggi. Controlla i log del server.","messageStatus": {diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex 1db55631d..1839e2c96 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -186,7 +186,8 @@"react": "메시지에 반응하지 못했습니다","delete": "메시지를 삭제하지 못했습니다","clickButton": "버튼 클릭에 실패했습니다",- "fileTooLarge": "파일이 너무 큽니다 (최대 18 MB)"+ "fileTooLarge": "파일이 너무 큽니다 (최대 18 MB)",+ "searchHitSessionNotReady": "이 메시지의 세션이 연결되어 있지 않습니다"},"loadMessagesError": "메시지를 불러올 수 없습니다. 서버 로그를 확인하세요.","messageStatus": {diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex d2028a571..18ef1f1c7 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -189,7 +189,8 @@"react": "Erro ao reagir à mensagem","delete": "Erro ao excluir a mensagem","clickButton": "Erro ao clicar no botão",- "fileTooLarge": "O arquivo é muito grande (máx. 18 MB)"+ "fileTooLarge": "O arquivo é muito grande (máx. 18 MB)",+ "searchHitSessionNotReady": "A sessão desta mensagem não está conectada"},"loadMessagesError": "Não foi possível carregar as mensagens. Verifique os registros do servidor.","messageStatus": {diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex dbbc299d6..4e4d80e50 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -186,7 +186,8 @@"react": "సందేశానికి ప్రతిస్పందించడం విఫలమైంది","delete": "సందేశాన్ని తొలగించడం విఫలమైంది","clickButton": "బటన్ క్లిక్ విఫలమైంది",- "fileTooLarge": "ఫైల్ చాలా పెద్దది (గరిష్టం 18 MB)"+ "fileTooLarge": "ఫైల్ చాలా పెద్దది (గరిష్టం 18 MB)",+ "searchHitSessionNotReady": "ఈ సందేశం యొక్క సెషన్ కనెక్ట్ కాలేదు"},"loadMessagesError": "సందేశాలను లోడ్ చేయడం సాధ్యం కాలేదు. సర్వర్ లాగ్లను తనిఖీ చేయండి.","messageStatus": {diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex b00f9c7f3..72e584cd3 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -186,7 +186,8 @@"react": "Mesaja tepki verilemedi","delete": "Mesaj silinemedi","clickButton": "Düğmeye tıklanamadı",- "fileTooLarge": "Dosya çok büyük (maks 18 MB)"+ "fileTooLarge": "Dosya çok büyük (maks 18 MB)",+ "searchHitSessionNotReady": "Bu mesajın oturumu bağlı değil"},"loadMessagesError": "Mesajlar yüklenemedi. Sunucu kayıtlarını kontrol edin.","messageStatus": {diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex 869ecb28b..2b4e1314a 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -186,7 +186,8 @@"react": "回应消息失败","delete": "删除消息失败","clickButton": "点击按钮失败",- "fileTooLarge": "文件过大(最大 18 MB)"+ "fileTooLarge": "文件过大(最大 18 MB)",+ "searchHitSessionNotReady": "此消息所属的会话未连接"},"loadMessagesError": "无法加载消息。请检查服务器日志。","messageStatus": {diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 372ded8a5..fa47c53c3 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -186,7 +186,8 @@"react": "回應訊息失敗","delete": "刪除訊息失敗","clickButton": "點擊按鈕失敗",- "fileTooLarge": "檔案過大(最大 18 MB)"+ "fileTooLarge": "檔案過大(最大 18 MB)",+ "searchHitSessionNotReady": "此訊息所屬的工作階段未連線"},"loadMessagesError": "無法載入訊息。請檢查伺服器日誌。","messageStatus": {diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsindex d5b0050c5..81ed1cd93 100644--- a/dashboard/src/pages/Chats.test.ts+++ b/dashboard/src/pages/Chats.test.ts@@ -15,7 +15,7 @@ import { test, before, afterEach } from 'node:test';import assert from 'node:assert/strict';import { createElement } from 'react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';-import type { Session, Chat, ChatMessage } from '../services/api';+import type { Session, Chat, ChatMessage, SearchHit } from '../services/api';import type { installJsdomGlobals as installJsdomGlobalsFn } from '../test-helpers/jsdom.ts';// socket.io-client resolves to a double under this runner (see vite-shim-hooks.mjs), which is what// lets a test deliver a server frame to the page's realtime handlers.@@ -37,6 +37,14 @@ const SESSION: Session = {const SESSION_2: Session = { ...SESSION, id: 'session-2', name: 'Second', phone: '15559876543' };let twoSessions = false;+// A third session the gateway lists but that the page may not offer, with the status the list reports.+// Its routes answer with the first session's fixtures, like session-2's.+const SESSION_3: Session = { ...SESSION, id: 'session-3', name: 'Third', phone: '15550004444' };+let thirdSessionStatus: Session['status'] | null = null;++// Hits the global search answers with.+let searchHits: SearchHit[] = [];+// Answers a session's chat list in place of the fixture, keyed by the session id in the URL (before// the rewrite below folds session-2 onto session-1), so a test can land two lists in any order.let chatsResponder: ((sessionId: string) => Promise<Response>) | null = null;@@ -251,7 +259,7 @@ function installFetchStub(): void {const method = init?.method ?? 'GET';const path = url.replace(/^https?:\/\/[^/]+/, '')- .replace(`/api/sessions/${SESSION_2.id}/`, `/api/sessions/${SESSION.id}/`);+ .replace(new RegExp(`/api/sessions/(${SESSION_2.id}|${SESSION_3.id})/`), `/api/sessions/${SESSION.id}/`);let body: unknown;if (typeof init?.body === 'string') {@@ -264,7 +272,9 @@ function installFetchStub(): void {fetchCalls.push({ method, path, body });if (method === 'GET' && path === '/api/sessions') {- return Promise.resolve(jsonResponse(twoSessions ? [SESSION, SESSION_2] : [SESSION]));+ const listed = twoSessions ? [SESSION, SESSION_2] : [SESSION];+ if (thirdSessionStatus) listed.push({ ...SESSION_3, status: thirdSessionStatus });+ return Promise.resolve(jsonResponse(listed));}if (method === 'GET' && path === '/api/infra/engines/current') {return Promise.resolve(jsonResponse({ engineType: 'baileys' }));@@ -330,7 +340,7 @@ function installFetchStub(): void {return Promise.resolve(jsonResponse({ messageId: 'wamid.out.document', timestamp: 1_700_000_100 }));}if (method === 'GET' && path.startsWith('/api/search?')) {- return Promise.resolve(jsonResponse({ hits: [], total: 0 }));+ return Promise.resolve(jsonResponse({ hits: searchHits, total: searchHits.length }));}if (method === 'POST' && path === `/api/sessions/${SESSION.id}/status/send-text`) {return Promise.resolve(jsonResponse({ success: true }));@@ -389,6 +399,8 @@ afterEach(() => {sendTextId = 'wamid.out.1';olderPageFails = false;chatsResponder = null;+ thirdSessionStatus = null;+ searchHits = [];});function renderChats(): { container: HTMLElement } {@@ -1232,6 +1244,64 @@ test('every message for a chat the sidebar does not list refetches the list, andawait screen.findByText('Dave');});+// A global-search hit in the third session, on Alice's chat.+const THIRD_SESSION_HIT: SearchHit = {+ messageId: 'db-9',+ waMessageId: 'wamid.third.1',+ sessionId: SESSION_3.id,+ chatId: CHAT.id,+ body: 'hello from the third session',+ snippet: 'hello from the <mark>third</mark> session',+ timestamp: 1_700_000_000,+ type: 'text',+ direction: 'incoming',+ from: CHAT.id,+};++async function clickSearchHit(container: HTMLElement): Promise<void> {+ const { screen, fireEvent, waitFor } = rtl;+ fireEvent.change(screen.getByLabelText('Search messages…'), { target: { value: 'third' } });+ const hit = await waitFor(() => {+ const found = container.querySelector('.global-search-hit');+ assert.ok(found, 'the search hit did not render');+ return found;+ });+ fireEvent.click(hit);+}++test('a search hit in a session that is not connected stays on the selected session', async () => {+ const { screen, waitFor } = rtl;+ thirdSessionStatus = 'disconnected';+ searchHits = [THIRD_SESSION_HIT];+ resetFetchCalls();+ const { container } = renderChats();+ await screen.findByText('Alice');++ await clickSearchHit(container);+ await screen.findByText('The session of this message is not connected');+ await waitFor(() => assert.equal(countFetchCalls('GET', '/api/sessions'), 2, 'the session list was not reread'));+ await flush();+ const select = container.querySelector('select.session-selector') as HTMLSelectElement;+ assert.equal(select.value, SESSION.id);+ assert.ok(screen.queryByText('Alice'), 'the chat list of the selected session is gone');+ assert.ok(!screen.queryByText('Failed to load chats'), 'the page tried to load the unconnected session');+});++test('a search hit in a session that connected after the page loaded opens it', async () => {+ const { screen, within, waitFor } = rtl;+ thirdSessionStatus = 'disconnected';+ searchHits = [THIRD_SESSION_HIT];+ const { container } = renderChats();+ await screen.findByText('Alice');++ thirdSessionStatus = 'ready';+ await clickSearchHit(container);+ const select = container.querySelector('select.session-selector') as HTMLSelectElement;+ await waitFor(() => assert.equal(select.value, SESSION_3.id));+ await waitFor(() => assert.ok(container.querySelector('.room-header'), "the hit's chat did not open"));+ await within(container.querySelector('.room-header') as HTMLElement).findByText('Alice');+});+test('changing the UI language keeps the selected session and the open chat', async () => {const { screen, fireEvent, within, waitFor, act } = rtl;const { default: i18n } = await import('../i18n/index.ts');diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 562a35976..4857277f8 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -733,7 +733,25 @@ export function Chats() {const pendingHitRef = useRef<{ chatId: string; waMessageId: string } | null>(null);const handleSearchHit = useCallback(- (hit: SearchHit) => {+ async (hit: SearchHit) => {+ // Search covers stored messages of every session, but the page can only open a ready one, and+ // its list is read on mount. A session missing from it is looked up again, since it may have+ // connected since; one that still is not ready is refused rather than selected with no chats.+ if (hit.sessionId !== selectedSessionId && !sessions.some(s => s.id === hit.sessionId)) {+ let ready: Session[];+ try {+ ready = (await sessionApi.list()).filter(s => s.status === 'ready');+ } catch (err) {+ showLoadError('chats.errors.loadSessions', err);+ return;+ }+ if (!ready.some(s => s.id === hit.sessionId)) {+ pendingHitRef.current = null;+ showWarningToast(t('chats.errors.searchHitSessionNotReady'));+ return;+ }+ setSessions(ready);+ }pendingHitRef.current = { chatId: hit.chatId, waMessageId: hit.waMessageId };if (hit.sessionId !== selectedSessionId) {// Switching session triggers loadChats; the effect below selects the chat once the list lands.@@ -762,7 +780,7 @@ export function Chats() {}}},- [selectedSessionId, chats, switchTab],+ [selectedSessionId, sessions, chats, switchTab, showLoadError, showWarningToast, t],);// After a session switch the chats list reloads — pick up the pending chat once it appears.