Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwebjs): retry a mid-navigation requestPairingCode instead of hanging

Yudhi Armyndharis66770baa8b64
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index 9746ad7aa..bbf3eb877 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -44,6 +44,24 @@ function isNavigationShapedInitRejection(reason: string): boolean {
return isExecutionContextDestroyedError(reason) || /window\.require is not a function/i.test(reason);
}
+/**
+ * requestPairingCode retry budget. WhatsApp Web reloads the QR page while UNPAIRED, so a pairing
+ * request can land mid-navigation and either reject fast ("Execution context was destroyed") or hang
+ * until Puppeteer's protocol timeout. Each attempt is bounded, and only the navigation/timeout shapes
+ * are retried; four attempts across ~1 minute cover several reload cycles, the page reboots in 2-3s.
+ */
+export const PAIRING_CODE_MAX_ATTEMPTS = 4;
+export const PAIRING_CODE_ATTEMPT_TIMEOUT_MS = 15_000;
+export const PAIRING_CODE_RETRY_DELAY_MS = 3_000;
+
+/** Sentinel for a per-attempt pairing timeout, so it is retried like a navigation error rather than propagated. */
+class PairingCodeAttemptTimeoutError extends Error {
+ constructor() {
+ super('requestPairingCode attempt timed out');
+ this.name = 'PairingCodeAttemptTimeoutError';
+ }
+}
+
// A post-READY page navigation (WhatsApp Web's ~5-minute first reload on a fresh pairing, a
// service-worker update, …) destroys the page's JS world; whatsapp-web.js re-injects on its own
// framenavigated handler (Client.js:504-513), but until WA Web has booted again getState() REJECTS,
@@ -1009,6 +1027,51 @@ export class WwebjsLifecycle {
if (!this.client || this.status !== EngineStatus.QR_READY) {
throw new EngineNotReadyError('Session is not waiting to be linked. Start it and wait for the QR stage.');
}
- return this.client.requestPairingCode(phoneNumber);
+ // WhatsApp Web reloads the QR page while UNPAIRED (roughly every 20s). A requestPairingCode that
+ // lands mid-navigation runs its in-page evaluate against a destroyed context: it either rejects
+ // with "Execution context was destroyed" or hangs until Puppeteer's protocol timeout (minutes),
+ // and the dashboard sits on "Creating pairing code..." with nothing ever returned. The navigation
+ // is transient (the page reboots in a few seconds), so bound each attempt and retry only the
+ // navigation/timeout shapes while the session is still at the QR stage. A real failure (an invalid
+ // number, an already-linked account) is not navigation-shaped and propagates on the first attempt.
+ let lastError: unknown;
+ for (let attempt = 1; attempt <= PAIRING_CODE_MAX_ATTEMPTS; attempt++) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ this.client.requestPairingCode(phoneNumber),
+ new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(() => reject(new PairingCodeAttemptTimeoutError()), PAIRING_CODE_ATTEMPT_TIMEOUT_MS);
+ timer.unref?.();
+ }),
+ ]);
+ } catch (error) {
+ lastError = error;
+ const reason = error instanceof Error ? error.message : String(error);
+ const transient =
+ error instanceof PairingCodeAttemptTimeoutError ||
+ isExecutionContextDestroyedError(reason) ||
+ /callfunctionon timed out|timed out\. increase the 'protocoltimeout'/i.test(reason);
+ if (!transient) {
+ throw error;
+ }
+ if (attempt < PAIRING_CODE_MAX_ATTEMPTS) {
+ await new Promise<void>(resolve => {
+ const t = setTimeout(resolve, PAIRING_CODE_RETRY_DELAY_MS);
+ t.unref?.();
+ });
+ // The reboot may have ended the QR window (linked, or torn down). Do not retry a dead session.
+ if (!this.client || this.status !== EngineStatus.QR_READY) {
+ throw new EngineNotReadyError('Session is no longer waiting to be linked.');
+ }
+ }
+ } finally {
+ if (timer) {
+ clearTimeout(timer);
+ }
+ }
+ }
+ // Every attempt hit a transient navigation/timeout: surface the last one rather than a hang.
+ throw lastError;
}
}
diff --git a/src/engine/adapters/wwebjs-pairing-code.spec.ts b/src/engine/adapters/wwebjs-pairing-code.spec.ts
new file mode 100644
index 000000000..1127ce3ca
--- /dev/null
+++ b/src/engine/adapters/wwebjs-pairing-code.spec.ts
@@ -0,0 +1,94 @@
+import {
+ WwebjsLifecycle,
+ type WwebjsLifecycleHost,
+ PAIRING_CODE_MAX_ATTEMPTS,
+ PAIRING_CODE_ATTEMPT_TIMEOUT_MS,
+ PAIRING_CODE_RETRY_DELAY_MS,
+} from './wwebjs-lifecycle';
+import { EngineStatus } from '../interfaces/whatsapp-engine.interface';
+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
+import type { Client } from 'whatsapp-web.js';
+
+/**
+ * WhatsApp Web reloads the QR page while UNPAIRED, so a requestPairingCode can land mid-navigation and
+ * either reject with "Execution context was destroyed" or hang until Puppeteer's protocol timeout.
+ * The call now bounds each attempt and retries the navigation/timeout shapes while still at QR_READY,
+ * so the dashboard gets a code instead of sitting on "Creating pairing code..." forever.
+ */
+function makeLifecycle(requestPairingCode: jest.Mock): WwebjsLifecycle {
+ const host = {
+ logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
+ config: { sessionId: 'sess', sessionDataPath: './data' },
+ } as unknown as WwebjsLifecycleHost;
+ const lc = new WwebjsLifecycle(host);
+ lc.status = EngineStatus.QR_READY;
+ lc.client = { requestPairingCode } as unknown as Client;
+ return lc;
+}
+
+describe('requestPairingCode retries a mid-navigation page', () => {
+ afterEach(() => jest.useRealTimers());
+
+ it('rejects before the QR stage without touching the client', async () => {
+ const requestPairingCode = jest.fn();
+ const lc = makeLifecycle(requestPairingCode);
+ lc.status = EngineStatus.INITIALIZING;
+ await expect(lc.requestPairingCode('628111')).rejects.toBeInstanceOf(EngineNotReadyError);
+ expect(requestPairingCode).not.toHaveBeenCalled();
+ });
+
+ it('retries a navigation-destroyed context and returns the code once the page reboots', async () => {
+ jest.useFakeTimers();
+ const requestPairingCode = jest
+ .fn()
+ .mockRejectedValueOnce(new Error('Execution context was destroyed, most likely because of a navigation.'))
+ .mockResolvedValueOnce('WXYZ1234');
+ const lc = makeLifecycle(requestPairingCode);
+
+ const pending = lc.requestPairingCode('628111');
+ await jest.advanceTimersByTimeAsync(PAIRING_CODE_RETRY_DELAY_MS + 10);
+
+ await expect(pending).resolves.toBe('WXYZ1234');
+ expect(requestPairingCode).toHaveBeenCalledTimes(2);
+ });
+
+ it('bounds a hanging attempt and gives up after the attempt budget', async () => {
+ jest.useFakeTimers();
+ const requestPairingCode = jest.fn().mockImplementation(() => new Promise<string>(() => undefined)); // never settles
+ const lc = makeLifecycle(requestPairingCode);
+
+ const pending = lc.requestPairingCode('628111');
+ pending.catch(() => undefined); // the rejection is asserted below; avoid an unhandled rejection warning
+ const total =
+ PAIRING_CODE_MAX_ATTEMPTS * PAIRING_CODE_ATTEMPT_TIMEOUT_MS +
+ (PAIRING_CODE_MAX_ATTEMPTS - 1) * PAIRING_CODE_RETRY_DELAY_MS +
+ 50;
+ await jest.advanceTimersByTimeAsync(total);
+
+ await expect(pending).rejects.toThrow(/attempt timed out/i);
+ expect(requestPairingCode).toHaveBeenCalledTimes(PAIRING_CODE_MAX_ATTEMPTS);
+ });
+
+ it('propagates a non-navigation failure on the first attempt (no wasted retries)', async () => {
+ const requestPairingCode = jest.fn().mockRejectedValue(new Error('phone number is not registered on WhatsApp'));
+ const lc = makeLifecycle(requestPairingCode);
+ await expect(lc.requestPairingCode('628111')).rejects.toThrow(/not registered/);
+ expect(requestPairingCode).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops retrying when the session leaves the QR stage between attempts', async () => {
+ jest.useFakeTimers();
+ const requestPairingCode = jest
+ .fn()
+ .mockRejectedValue(new Error('Execution context was destroyed, most likely because of a navigation.'));
+ const lc = makeLifecycle(requestPairingCode);
+
+ const pending = lc.requestPairingCode('628111');
+ pending.catch(() => undefined);
+ lc.status = EngineStatus.READY; // linked while the first retry delay is pending
+ await jest.advanceTimersByTimeAsync(PAIRING_CODE_RETRY_DELAY_MS + 10);
+
+ await expect(pending).rejects.toBeInstanceOf(EngineNotReadyError);
+ expect(requestPairingCode).toHaveBeenCalledTimes(1);
+ });
+});