Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): drop a pairing code answered after its modal closed
Yudhi Armyndharis2df40520c833
diff --git a/dashboard/src/hooks/useSessionPairing.ts b/dashboard/src/hooks/useSessionPairing.tsindex dbb252243..9cb422911 100644--- a/dashboard/src/hooks/useSessionPairing.ts+++ b/dashboard/src/hooks/useSessionPairing.ts@@ -56,6 +56,11 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Useconst [pairingError, setPairingError] = useState<string | null>(null);const qrRefreshInterval = useRef<ReturnType<typeof setInterval> | null>(null);+ // Bumped whenever the modal opens, closes or is dismissed. A pairing-code request is not cancelled+ // by any of those, so its answer is applied only while the modal it was sent from is still the one+ // on screen: not in a modal since opened for another session, nor in the same session's modal reset+ // to a blank form.+ const pairingGen = useRef(0);const fetchQR = useCallback(async (sessionId: string) => {@@ -107,6 +112,8 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Use}, [qrData, fetchQR]);const handleCloseQRModal = useCallback(() => {+ pairingGen.current += 1;+ setRequestingPairing(false);setQrData(null);setPairingMode(false);setPhoneNumber('');@@ -134,15 +141,16 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: UsesetPairingError(t('sessions.pairing.invalidPhone'));return;}+ const gen = pairingGen.current;try {setRequestingPairing(true);setPairingError(null);const res = await sessionApi.requestPairingCode(qrData.sessionId, phoneNumber.trim());- setPairingCode(res.pairingCode);+ if (gen === pairingGen.current) setPairingCode(res.pairingCode);} catch (err) {- setPairingError(err instanceof Error ? err.message : t('common.errorGeneric'));+ if (gen === pairingGen.current) setPairingError(err instanceof Error ? err.message : t('common.errorGeneric'));} finally {- setRequestingPairing(false);+ if (gen === pairingGen.current) setRequestingPairing(false);}};@@ -153,10 +161,12 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Useconst sessionName = session?.name || '';// Reset any pairing sub-state from a previous open so a freshly opened modal never shows a// stale code/phone belonging to a different session.+ pairingGen.current += 1;setPairingMode(false);setPhoneNumber('');setPairingCode(null);setPairingError(null);+ setRequestingPairing(false);// Show loading state immediately so the modal opens and polling starts// even before Chromium has finished initializing.setQrData({ sessionId: id, sessionName, qrCode: '' });@@ -198,6 +208,7 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: UsesetQrData(current => {if (current?.sessionId !== sessionId) return current;if (onlyIfBlank && current.qrCode) return current;+ pairingGen.current += 1;return null;});}, []);diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.tsindex 9e097ae68..29b8d16de 100644--- a/dashboard/src/pages/Sessions.test.ts+++ b/dashboard/src/pages/Sessions.test.ts@@ -103,6 +103,7 @@ function resetFetchCalls(): void {stopFailure = null;qrGate = null;listGate = null;+ pairingGate = null;}function findFetchCall(method: string, path: string): FetchCall | undefined {@@ -136,6 +137,8 @@ let qrGate: { sessionId: string; until: Promise<void> } | null = null;// When set, the next GET /api/sessions reads the rows as they are when it arrives but answers only once// this settles, so a test can land an older read after a newer one. Spent by that one read.let listGate: Promise<void> | null = null;+// When set, POST .../pairing-code answers only once this settles.+let pairingGate: Promise<void> | null = null;let sessionProxy = {enabled: false,proxyType: null as string | null,@@ -246,7 +249,9 @@ function installFetchStub(): void {const pairingMatch = path.match(/^\/api\/sessions\/([^/]+)\/pairing-code$/);if (method === 'POST' && pairingMatch) {- return Promise.resolve(jsonResponse({ pairingCode: '12345678', status: 'qr_ready' }));+ const answer = () => jsonResponse({ pairingCode: '12345678', status: 'qr_ready' });+ if (pairingGate) return pairingGate.then(answer);+ return Promise.resolve(answer());}const lifecycleMatch = path.match(/^\/api\/sessions\/([^/]+)\/(start|stop|logout|force-kill)$/);@@ -592,6 +597,48 @@ test('a QR answer that lands after its modal closed changes nothing', async () =}});+// Closing the modal does not cancel a pairing-code request either (whatsapp-web.js can take seconds to+// answer). Its code must not appear in a modal opened since, for another session or for the same one+// reset to a blank form, and that modal must not start with Generate stuck on the old request.+test('a pairing code that lands after its modal closed changes nothing', async () => {+ const { screen, fireEvent, within, act } = rtl;+ resetFetchCalls();+ const other: Session = { ...SESSION_QR, id: 'sess-qr-3', name: 'third-device' };+ SESSIONS.push(other);+ try {+ renderSessions();+ const card = (await screen.findByText('new-device')).closest('.session-card') as HTMLElement;+ const otherCard = screen.getByText('third-device').closest('.session-card') as HTMLElement;+ const settle = () => act(() => new Promise<void>(resolve => setTimeout(resolve, 20)));++ for (const reopen of [otherCard, card]) {+ let release: () => void = () => {};+ pairingGate = new Promise<void>(resolve => (release = resolve));+ fireEvent.click(within(card).getByRole('button', { name: 'Show QR' }));+ await screen.findByAltText('QR');+ fireEvent.click(screen.getByRole('tab', { name: 'Link with Phone Number' }));+ fireEvent.change(screen.getByLabelText('Phone Number'), { target: { value: '919876543210' } });+ fireEvent.click(screen.getByRole('button', { name: 'Generate Pairing Code' }));+ await screen.findByText('Generating pairing code...');+ fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Close' }));++ fireEvent.click(within(reopen).getByRole('button', { name: 'Show QR' }));+ await screen.findByAltText('QR');+ fireEvent.click(screen.getByRole('tab', { name: 'Link with Phone Number' }));+ const dialog = screen.getByRole('dialog');+ assert.ok(!within(dialog).queryByText('Generating pairing code...'), 'Generate stayed stuck on the old request');+ release();+ await settle();++ assert.ok(!dialog.querySelector('.pairing-code-display'), 'a late pairing code landed in a modal opened since');+ assert.ok(within(dialog).queryByRole('tab', { name: 'QR Code' }), 'a late pairing code hid the tab bar');+ fireEvent.click(within(dialog).getByRole('button', { name: 'Close' }));+ }+ } 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.