Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): re-read sessions when a failed feed recovers
Yudhi Armyndharis59f76aac3449
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 039dae648..a92395488 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,7 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The Baileys live path drops contentless protocol traffic (sender-key distributions, message-history notices) instead of delivering it as a bodyless `unknown` `message.received`, matching what the history path already does ([#1568](https://github.com/rmyndharis/OpenWA/issues/1568)). Thanks @berodcdev for the report.- A Baileys reconnect loop is observable: `lastError` on the session, a `session.reconnect_loop` webhook every fifth attempt, and reconnect metrics; a connection attempt refused at the WebSocket upgrade is closed and retried instead of leaving the session at `initializing` ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.- The dashboard session card keeps the phone number, session id and last-active time while a linked session reconnects, instead of the pairing placeholder ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.-- The Sessions page reports a dead live-event feed and re-reads the list once the feed recovers.+- The Sessions page reports a dead live-event feed, and both it and the Chats page re-read their data once the feed recovers, including a feed that never connected.- A Baileys media download aborted at `MEDIA_DOWNLOAD_MAX_BYTES` reports the bytes received as `sizeBytes`, and a timed-out one its declared size, instead of the cap.- The webhook docs state that at the default limits media above about 768 KiB reaches webhooks as the omitted marker, and how to raise both limits ([#1569](https://github.com/rmyndharis/OpenWA/issues/1569)). Thanks @Magnarks for the report.- The takeover sweep marks sessions left `ready` or `initializing` by a node that never returned disconnected, regardless of `AUTO_START_SESSIONS`.diff --git a/dashboard/src/hooks/useSessionFeed.ts b/dashboard/src/hooks/useSessionFeed.tsindex ddaa20ea1..39bceb75f 100644--- a/dashboard/src/hooks/useSessionFeed.ts+++ b/dashboard/src/hooks/useSessionFeed.ts@@ -20,8 +20,9 @@ export interface UseSessionFeedArgs {onSessionStatus: (event: { sessionId: string; status: string }) => void;onSessionRestriction?: (event: { sessionId: string }) => void;/**- * Fired once per RECONNECT, never on the first connect: every push that happened while the socket- * was down is gone, so the caller must re-read the list it holds in local state.+ * Fired once per RECONNECT, never on the first connect unless the feed failed before it: every push+ * that happened while the socket was down is gone, so the caller must re-read the list it holds in+ * local state.*/onReconnect?: () => void;}@@ -105,8 +106,10 @@ export function useSessionFeed({// caller keeps its list in local state with no polling behind it, so a card would render its// pre-gap status until the operator reloaded the page. Tell the caller to re-read, on the RECONNECT// only and never on the first connect (nothing is cached yet, and the caller already fetched at- // mount). Same pure transition the Chats page uses, and idempotent: a re-run caused by a changed- // `onReconnect` identity sees the gap marker already cleared and does not fetch twice.+ // mount), unless the feed failed first: the banner's retry then recovers a feed that may never have+ // connected, and the mount read is as stale as any gap. Same pure transition the Chats page uses,+ // and idempotent: a re-run caused by a changed `onReconnect` identity sees the gap marker already+ // cleared and does not fetch twice.const hadConnected = useRef(false);const wasDisconnected = useRef(false);useEffect(() => {@@ -114,11 +117,12 @@ export function useSessionFeed({isConnected,hadConnected: hadConnected.current,wasDisconnected: wasDisconnected.current,+ connectionFailed,});hadConnected.current = decision.hadConnected;wasDisconnected.current = decision.wasDisconnected;if (decision.invalidate) onReconnect?.();- }, [isConnected, onReconnect]);+ }, [isConnected, connectionFailed, onReconnect]);// In per-session mode, sessions loaded/created after the fallback still need their rooms.useEffect(() => {diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsindex 82510d8fb..ad8d7796b 100644--- a/dashboard/src/pages/Chats.test.ts+++ b/dashboard/src/pages/Chats.test.ts@@ -19,7 +19,7 @@ import type { Session, Chat, ChatMessage } 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.-import { lastSocket, resetSocketDouble } from '../test-helpers/socket-io-double.ts';+import { holdConnect, lastSocket, resetSocketDouble } from '../test-helpers/socket-io-double.ts';// ── Fixtures + fetch stub ────────────────────────────────────────────────────@@ -451,6 +451,36 @@ test('status compose modal posts a text status with the baileys recipient allow-});});+test('Refresh on a feed that never connected refetches the open thread once the socket is back', async () => {+ const { screen, fireEvent, within, waitFor, act } = rtl;+ resetFetchCalls();+ holdConnect();+ const { container } = renderChats();++ await screen.findByText('Main (15551234567)');+ fireEvent.click(await screen.findByText('Alice'));+ await within(container.querySelector('.room-messages') as HTMLElement).findByText('hello from alice');+ const threadReads = (): number =>+ fetchCalls.filter(c => c.method === 'GET' && c.path.startsWith(`/api/sessions/${SESSION.id}/messages?`)).length;+ const readsBeforeRetry = threadReads();++ // A rejected handshake delivers its connect and the server's close in one batch, so this socket+ // never renders as connected, and the thread misses whatever arrives while the banner is up.+ const rejected = lastSocket();+ assert.ok(rejected, 'expected the page to have opened a socket');+ act(() => {+ rejected.receive('connect');+ rejected.receive('disconnect', 'io server disconnect');+ });+ const banner = await screen.findByRole('alert');+ fireEvent.click(within(banner).getByRole('button', { name: 'Refresh' }));+ const redialed = lastSocket();+ assert.ok(redialed && redialed !== rejected, 'expected Refresh to open a fresh socket');+ act(() => redialed.receive('connect'));++ await waitFor(() => assert.equal(threadReads(), readsBeforeRetry + 1));+});+test('a typed draft survives closing and reopening the room', async () => {const { screen, fireEvent, within } = rtl;resetFetchCalls();diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 1b933d44c..1b7951fa7 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -542,7 +542,8 @@ export function Chats() {// A transient WebSocket gap means message.received/ack/revoke events were missed, and the chat// cache uses staleTime: Infinity so it won't refetch on its own. On a reconnect (isConnected// false→true after a prior connect), invalidate the active session's messages so the thread the- // gap left stale refreshes. The transition logic is unit-tested in utils/reconnectState.+ // gap left stale refreshes. A failed feed counts as a gap even if it never connected, so the+ // banner's retry refreshes too. The transition logic is unit-tested in utils/reconnectState.const reconnectHadConnected = useRef(false);const reconnectWasDisconnected = useRef(false);useEffect(() => {@@ -550,6 +551,7 @@ export function Chats() {isConnected,hadConnected: reconnectHadConnected.current,wasDisconnected: reconnectWasDisconnected.current,+ connectionFailed,});reconnectHadConnected.current = decision.hadConnected;reconnectWasDisconnected.current = decision.wasDisconnected;@@ -559,7 +561,7 @@ export function Chats() {// otherwise stay invisible until a focus refetch.queryClient.invalidateQueries({ queryKey: ['contact-statuses', selectedSessionId] });}- }, [isConnected, selectedSessionId, queryClient]);+ }, [isConnected, connectionFailed, selectedSessionId, queryClient]);useEffect(() => {if (selectedSessionId && isConnected) {diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.tsindex 77ce843ee..22124f04d 100644--- a/dashboard/src/pages/Sessions.test.ts+++ b/dashboard/src/pages/Sessions.test.ts@@ -18,6 +18,7 @@ import { createElement } from 'react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import type { Session } from '../services/api';import type { installJsdomGlobals as installJsdomGlobalsFn } from '../test-helpers/jsdom.ts';+import { holdConnect, lastSocket, resetSocketDouble } from '../test-helpers/socket-io-double.ts';// ── Fixtures + fetch stub ────────────────────────────────────────────────────@@ -94,6 +95,7 @@ function resetFetchCalls(): void {fetchCalls.length = 0;sessionProxy = { enabled: false, proxyType: null, proxyHost: null, hasCredentials: false };proxyGetFails = false;+ sessionListFailures = 0;}function findFetchCall(method: string, path: string): FetchCall | undefined {@@ -108,6 +110,8 @@ function findFetchCall(method: string, path: string): FetchCall | undefined {let sessionConfig = { autoRejectCalls: false, maxReconnectAttempts: null as number | null, reconnectBaseDelay: 5000 };let configPatchFails = false;let proxyGetFails = false;+// How many of the next GET /api/sessions reads fail, as they do while the gateway is down.+let sessionListFailures = 0;let sessionProxy = {enabled: false,proxyType: null as string | null,@@ -131,7 +135,13 @@ function installFetchStub(): void {}fetchCalls.push({ method, path, body });- if (method === 'GET' && path === '/api/sessions') return Promise.resolve(jsonResponse(SESSIONS));+ if (method === 'GET' && path === '/api/sessions') {+ if (sessionListFailures > 0) {+ sessionListFailures -= 1;+ return Promise.resolve(jsonResponse({ message: 'gateway unavailable' }, 503));+ }+ return Promise.resolve(jsonResponse(SESSIONS));+ }if (method === 'POST' && path === '/api/sessions') {const payload = body as { name?: string; proxyUrl?: string; proxyType?: string } | undefined;@@ -236,9 +246,9 @@ before(async () => {// RoleProvider seeds from localStorage; 'admin' makes canWrite true, or every action button// (New Session, Stop/Start, Unlink, Delete, Kill Stuck) is hidden and there is nothing to test.window.localStorage.setItem('openwa_user_role', 'admin');- // Deliberately NOT setting sessionStorage['openwa_api_key']: useWebSocket.connect() reads it and- // bails with a console.warn when it's absent. Setting it would make socket.io actually dial- // http://localhost/events and hit ECONNREFUSED in this environment.+ // Deliberately NOT setting sessionStorage['openwa_api_key'] here: useWebSocket.connect() bails+ // with a console.warn when it's absent, so the page opens no socket. A case that drives the live+ // feed sets the key itself; the client it reaches is the socket.io double, which dials nothing.// Awaited, not just imported: catalogues are fetched now, so the import only starts the load and// the English copy these tests query by name renders as a raw key until it arrives.const { i18nReady } = await import('../i18n/index.ts');@@ -251,6 +261,8 @@ before(async () => {afterEach(() => {rtl.cleanup();+ window.sessionStorage.removeItem('openwa_api_key');+ resetSocketDouble();queryClient?.clear();queryClient = undefined;});@@ -469,6 +481,46 @@ test('an unrestricted session shows no restriction row', async () => {assert.equal(within(card).queryByText('Restriction'), null);});+// ── Live feed banner ─────────────────────────────────────────────────────────++test('Refresh on a feed that never connected re-reads the list once the socket is back', async () => {+ const { screen, fireEvent, waitFor, act, within } = rtl;+ resetFetchCalls();+ sessionListFailures = 1;+ window.sessionStorage.setItem('openwa_api_key', 'test-key');+ holdConnect();+ renderSessions();++ // The gateway is down at mount: the list read fails, and nothing is rendered to go stale.+ await screen.findByText('gateway unavailable');+ const listReads = (): number => fetchCalls.filter(c => c.method === 'GET' && c.path === '/api/sessions').length;+ assert.equal(listReads(), 1);++ // A rejected handshake: socket.io decodes the CONNECT ack and the server's close from one polling+ // payload, so React batches both handlers and `isConnected` never renders true on this mount.+ const rejected = lastSocket();+ assert.ok(rejected, 'expected the page to have opened a socket');+ act(() => {+ rejected.receive('connect');+ rejected.receive('disconnect', 'io server disconnect');+ });+ const banner = await screen.findByRole('alert');+ screen.getByText('Live updates disconnected');++ fireEvent.click(within(banner).getByRole('button', { name: 'Refresh' }));+ const redialed = lastSocket();+ assert.ok(redialed && redialed !== rejected, 'expected Refresh to open a fresh socket');+ act(() => redialed.receive('connect'));++ // Every push sent while the feed was dead is gone, so the recovered page must re-read the list, and+ // the error from the failed mount read must not sit on top of the cards it now shows.+ await waitFor(() => assert.equal(listReads(), 2));+ await screen.findByText('new-device');+ // Compared as booleans: a failing assert.equal renders both operands, and a jsdom node never finishes.+ assert.equal(screen.queryByText('gateway unavailable') === null, true, 'the failed read error is still shown');+ assert.equal(screen.queryByRole('alert') === null, true, 'the feed banner is still shown');+});+// ── Auto-reject toggle ───────────────────────────────────────────────────────async function openDetailFor(name: string): Promise<HTMLInputElement> {diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex a4f8a2630..5ea661023 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -107,6 +107,9 @@ export function Sessions() {if (!initialLoadDone.current) setLoading(true);const data = await sessionApi.list();setSessions(data);+ // The list is current again, so an error left by an earlier failed read (or a create, whose toast+ // already reported it) no longer describes the page.+ setError(null);// Keep the shared React Query cache (read by the Dashboard via useSessionsQuery /// useSessionStatsQuery) in sync after this page's mutations reload local state — otherwise the// Dashboard shows stale session counts/status. This runs on every reload (mount / WS-failed /diff --git a/dashboard/src/test-helpers/socket-io-double.ts b/dashboard/src/test-helpers/socket-io-double.tsindex d650fae42..e5600ec37 100644--- a/dashboard/src/test-helpers/socket-io-double.ts+++ b/dashboard/src/test-helpers/socket-io-double.ts@@ -25,7 +25,7 @@ class FakeSocket {this.listeners.set(event, set);// The real client fires 'connect' asynchronously after the handshake; do it on registration so// a page that gates its subscribe on connection reaches the same state.- if (event === 'connect') queueMicrotask(() => listener());+ if (event === 'connect' && autoConnect) queueMicrotask(() => listener());return this;}@@ -51,6 +51,7 @@ class FakeSocket {}let last: FakeSocket | null = null;+let autoConnect = true;export function io(): FakeSocket {last = new FakeSocket();@@ -62,8 +63,17 @@ export function lastSocket(): FakeSocket | null {return last;}+/**+ * Stop sockets from firing 'connect' on registration, so a test can deliver it with+ * `receive('connect')` in the same batch as the frames a real server sends alongside it.+ */+export function holdConnect(): void {+ autoConnect = false;+}+export function resetSocketDouble(): void {last = null;+ autoConnect = true;}// A VALUE export, not `export type`: useWebSocket imports `Socket` from a value position, and onlydiff --git a/dashboard/src/utils/reconnectState.test.ts b/dashboard/src/utils/reconnectState.test.tsindex d2ebc6cad..54a5fb873 100644--- a/dashboard/src/utils/reconnectState.test.ts+++ b/dashboard/src/utils/reconnectState.test.ts@@ -3,40 +3,57 @@ import assert from 'node:assert/strict';import { nextReconnectState } from './reconnectState.ts';test('initial connect (never connected before): no invalidate', () => {- assert.deepEqual(nextReconnectState({ isConnected: true, hadConnected: false, wasDisconnected: false }), {- invalidate: false,- hadConnected: true,- wasDisconnected: false,- });+ assert.deepEqual(+ nextReconnectState({ isConnected: true, hadConnected: false, wasDisconnected: false, connectionFailed: false }),+ { invalidate: false, hadConnected: true, wasDisconnected: false },+ );});test('disconnect before any connect (noise): no gap marked, no invalidate', () => {- assert.deepEqual(nextReconnectState({ isConnected: false, hadConnected: false, wasDisconnected: false }), {- invalidate: false,- hadConnected: false,- wasDisconnected: false,- });+ assert.deepEqual(+ nextReconnectState({ isConnected: false, hadConnected: false, wasDisconnected: false, connectionFailed: false }),+ { invalidate: false, hadConnected: false, wasDisconnected: false },+ );});test('disconnect after the first connect: mark a gap, no invalidate', () => {- assert.deepEqual(nextReconnectState({ isConnected: false, hadConnected: true, wasDisconnected: false }), {- invalidate: false,- hadConnected: true,- wasDisconnected: true,- });+ assert.deepEqual(+ nextReconnectState({ isConnected: false, hadConnected: true, wasDisconnected: false, connectionFailed: false }),+ { invalidate: false, hadConnected: true, wasDisconnected: true },+ );});test('reconnect after a gap (wasDisconnected): invalidate', () => {- assert.deepEqual(nextReconnectState({ isConnected: true, hadConnected: true, wasDisconnected: true }), {- invalidate: true,- hadConnected: true,- wasDisconnected: false,- });+ assert.deepEqual(+ nextReconnectState({ isConnected: true, hadConnected: true, wasDisconnected: true, connectionFailed: false }),+ { invalidate: true, hadConnected: true, wasDisconnected: false },+ );});test('stays connected: no invalidate, stays hadConnected', () => {- assert.deepEqual(nextReconnectState({ isConnected: true, hadConnected: true, wasDisconnected: false }), {- invalidate: false,+ assert.deepEqual(+ nextReconnectState({ isConnected: true, hadConnected: true, wasDisconnected: false, connectionFailed: false }),+ { invalidate: false, hadConnected: true, wasDisconnected: false },+ );+});++test('a feed that failed before it ever connected marks a gap', () => {+ assert.deepEqual(+ nextReconnectState({ isConnected: false, hadConnected: false, wasDisconnected: false, connectionFailed: true }),+ { invalidate: false, hadConnected: false, wasDisconnected: true },+ );+});++test('the gap survives the retry clearing connectionFailed, so the first connect after it invalidates', () => {+ const retrying = nextReconnectState({+ isConnected: false,+ hadConnected: false,+ wasDisconnected: true,+ connectionFailed: false,+ });+ assert.deepEqual(retrying, { invalidate: false, hadConnected: false, wasDisconnected: true });+ assert.deepEqual(nextReconnectState({ ...retrying, isConnected: true, connectionFailed: false }), {+ invalidate: true,hadConnected: true,wasDisconnected: false,});diff --git a/dashboard/src/utils/reconnectState.ts b/dashboard/src/utils/reconnectState.tsindex 5bd2eadb2..b6277342f 100644--- a/dashboard/src/utils/reconnectState.ts+++ b/dashboard/src/utils/reconnectState.ts@@ -2,6 +2,8 @@ export interface ReconnectState {isConnected: boolean;hadConnected: boolean;wasDisconnected: boolean;+ /** The socket gave up or the server closed it: dead until the user retries. */+ connectionFailed: boolean;}export interface ReconnectDecision {@@ -24,6 +26,9 @@ export interface ReconnectDecision {* - Connect with a marked gap: RECONNECT — invalidate, then clear the gap marker.* - Disconnect before any connect (transient noise on mount): no gap marked (avoid a spurious first-* connect invalidate if isConnected toggles false→true before the real first connect).+ * - Failed feed (connectionFailed), even one that never connected: mark a gap, and keep it while the+ * retry clears the flag. The data read at mount is older than the failure, and a rejected handshake+ * can deliver its connect and its close in one batch, so isConnected may never have rendered true.*/export function nextReconnectState(state: ReconnectState): ReconnectDecision {if (state.isConnected) {@@ -36,6 +41,6 @@ export function nextReconnectState(state: ReconnectState): ReconnectDecision {return {invalidate: false,hadConnected: state.hadConnected,- wasDisconnected: state.hadConnected,+ wasDisconnected: state.wasDisconnected || state.hadConnected || state.connectionFailed,};}