Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): drop a QR answer for a modal that has since closed
Yudhi Armyndharis45799c594bb5
diff --git a/dashboard/src/hooks/useSessionPairing.ts b/dashboard/src/hooks/useSessionPairing.tsindex 29c1b7667..dbb252243 100644--- a/dashboard/src/hooks/useSessionPairing.ts+++ b/dashboard/src/hooks/useSessionPairing.ts@@ -56,7 +56,6 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Useconst [pairingError, setPairingError] = useState<string | null>(null);const qrRefreshInterval = useRef<ReturnType<typeof setInterval> | null>(null);- const currentSessionName = useRef<string>('');const fetchQR = useCallback(async (sessionId: string) => {@@ -66,7 +65,6 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Useconst currentSession = sessionsRef.current.find(s => s.id === sessionId);if (currentSession?.status === 'ready') {setQrData(null);- currentSessionName.current = '';return;}// Poll only while a QR actually exists to refresh (qr_ready): before that the endpoint 400s@@ -74,10 +72,11 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Useif (currentSession?.status !== 'qr_ready') return;try {const qr = await sessionApi.getQR(sessionId);- setQrData({ sessionId, sessionName: currentSessionName.current, qrCode: qr.qrCode });+ // Every write after an await is keyed on the session: the modal may have been closed, or+ // opened for another session, while the request was in flight.+ setQrData(cur => (cur?.sessionId === sessionId ? { ...cur, qrCode: qr.qrCode } : cur));if (qr.status === 'ready') {- setQrData(null);- currentSessionName.current = '';+ setQrData(cur => (cur?.sessionId === sessionId ? null : cur));reloadSessions();}} catch {@@ -88,8 +87,7 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Useconst updated = await sessionApi.get(sessionId).catch(() => null);const stillInitializing = updated && ['initializing', 'qr_ready', 'authenticating'].includes(updated.status);if (!stillInitializing) {- setQrData(null);- currentSessionName.current = '';+ setQrData(cur => (cur?.sessionId === sessionId ? null : cur));reloadSessions();}}@@ -99,7 +97,6 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: UseuseEffect(() => {if (qrData) {- currentSessionName.current = qrData.sessionName;qrRefreshInterval.current = setInterval(() => {fetchQR(qrData.sessionId);}, 5000);@@ -163,14 +160,14 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Use// Show loading state immediately so the modal opens and polling starts// even before Chromium has finished initializing.setQrData({ sessionId: id, sessionName, qrCode: '' });- currentSessionName.current = sessionName;// Eager-fetch only when a QR already exists (qr_ready): before that the endpoint 400s BY DESIGN// (the engine hasn't produced one), and the WS session.qr push + gated 5s poll deliver it// without spamming the console with expected failures.if (session?.status === 'qr_ready') {try {const qr = await sessionApi.getQR(id);- setQrData({ sessionId: id, sessionName, qrCode: qr.qrCode });+ // Only into the modal still open for this session, as in fetchQR.+ setQrData(cur => (cur?.sessionId === id ? { ...cur, qrCode: qr.qrCode } : cur));} catch (err) {console.error('Failed to get QR:', err);// Do not clear qrData here — keep the loading modal open so thediff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.tsindex 1d29d8e85..4133a010c 100644--- a/dashboard/src/pages/Sessions.test.ts+++ b/dashboard/src/pages/Sessions.test.ts@@ -101,6 +101,7 @@ function resetFetchCalls(): void {startGate = null;startResult = null;stopFailure = null;+ qrGate = null;}function findFetchCall(method: string, path: string): FetchCall | undefined {@@ -129,6 +130,8 @@ let startResult: { answer: Partial<Session>; leaves?: Partial<Session> } | nulllet stopFailure: { status: number; message: string } | null = null;// When set, POST .../start answers, whichever way it answers, only once this settles.let startGate: Promise<void> | null = null;+// When set, GET .../qr for that one session answers only once `until` settles.+let qrGate: { sessionId: string; until: Promise<void> } | null = null;let sessionProxy = {enabled: false,proxyType: null as string | null,@@ -226,7 +229,9 @@ function installFetchStub(): void {if (method === 'GET' && qrMatch) {const found = SESSIONS.find(s => s.id === qrMatch[1]);if (!found) return Promise.resolve(jsonResponse({ message: 'not found' }, 404));- return Promise.resolve(jsonResponse({ qrCode: 'data:image/png;base64,FAKE', status: found.status }));+ const answer = () => jsonResponse({ qrCode: 'data:image/png;base64,FAKE', status: found.status });+ if (qrGate?.sessionId === found.id) return qrGate.until.then(answer);+ return Promise.resolve(answer());}const pairingMatch = path.match(/^\/api\/sessions\/([^/]+)\/pairing-code$/);@@ -539,6 +544,44 @@ test('stopping a session dismisses its own open QR modal', async () => {});});+// Closing the modal does not cancel a GET .../qr already in flight. Its late answer must not reopen+// the closed modal, nor replace the modal the operator has since opened for another session.+test('a QR answer that lands after its modal closed changes nothing', async () => {+ const { screen, fireEvent, within, waitFor } = rtl;+ resetFetchCalls();+ const other: Session = { ...SESSION_QR, id: 'sess-qr-2', name: 'second-device' };+ SESSIONS.push(other);+ try {+ renderSessions();+ const card = (await screen.findByText('new-device')).closest('.session-card') as HTMLElement;+ const otherCard = screen.getByText('second-device').closest('.session-card') as HTMLElement;+ const closeModal = () => fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Close' }));++ let release: () => void = () => {};+ qrGate = { sessionId: SESSION_QR.id, until: new Promise<void>(resolve => (release = resolve)) };+ fireEvent.click(within(card).getByRole('button', { name: 'Show QR' }));+ await screen.findByRole('dialog');+ closeModal();+ release();+ await waitFor(() => assert.ok(findFetchCall('GET', `/api/sessions/${SESSION_QR.id}/qr`)));+ await new Promise(resolve => setTimeout(resolve, 50));+ assert.ok(!screen.queryByRole('dialog'), 'a late QR answer reopened the closed modal');++ qrGate = { sessionId: SESSION_QR.id, until: new Promise<void>(resolve => (release = resolve)) };+ fireEvent.click(within(card).getByRole('button', { name: 'Show QR' }));+ await screen.findByRole('dialog');+ closeModal();+ fireEvent.click(within(otherCard).getByRole('button', { name: 'Show QR' }));+ await screen.findByAltText('QR');+ release();+ await new Promise(resolve => setTimeout(resolve, 50));+ const dialog = screen.getByRole('dialog');+ assert.ok(within(dialog).queryByText('second-device'), "a late QR answer replaced another session's modal");+ } finally {+ SESSIONS.pop();+ }+});+// A node that died mid-pairing leaves a row reading `qr_ready` with no engine behind it. Reconnect on// that card has to start the session: the QR modal alone polls GET /qr, which answers 400 until one// is started.