Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwjs): cancel an abandoned pairing attempt before retrying

Yudhi Armyndharis0262d75fbef4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cc75ecbbb..699fae752 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,6 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- An ingress route whose manifest carries a non-string ack body, status or header is answered rather than failing with `500`; a manifest is third-party JSON and the loader does not type-check every leaf.
- Uploading a zip whose trailer parses but whose directory does not answers `400`, not `500`.
- A `socks5://` or `socks4://` proxy at an IPv6 literal connects: the brackets `URL` keeps were going on the wire as part of a hostname.
+- A whatsapp-web.js pairing-code retry cancels the attempt it abandoned before starting the next one. The per-attempt timeout stops waiting but does not stop the library's in-page linking flow, which keeps re-requesting a code on its own interval, so retries used to stack competing flows over one device slot.
- A Baileys session whose credentials carry no LID of their own no longer reports a `group.join` for a group it created itself: every LID comparison answered false, so the creator was never recognised. The session's own LID mapping settles it instead.
- Starting a session that turns out to be linked already no longer opens a QR modal over it, which then polled for a code that could never arrive. The decision now reads the list the dashboard re-reads after the start, not the state it held before it.
- Escape dismisses the Chats emoji picker instead of closing the whole conversation behind it.
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index 0788cdfd8..9a2079af1 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -1072,6 +1072,13 @@ export class WwebjsLifecycle {
throw error;
}
if (attempt < PAIRING_CODE_MAX_ATTEMPTS) {
+ // The race abandons the losing attempt, it does not cancel it: the library's in-page
+ // linking flow keeps running, and it arms an interval that re-requests a code every few
+ // minutes. Starting the next attempt on top of that leaves two flows competing over one
+ // device slot. Ask the library to stop the abandoned one first, best-effort: it is itself a
+ // page evaluate, and the page is exactly what is unwell here, so its own failure must not
+ // replace the transient reason this retry exists for.
+ await this.cancelAbandonedPairing();
await new Promise<void>(resolve => {
const t = setTimeout(resolve, PAIRING_CODE_RETRY_DELAY_MS);
t.unref?.();
@@ -1096,4 +1103,24 @@ export class WwebjsLifecycle {
`${lastError instanceof Error ? lastError.message : String(lastError)}`,
);
}
+
+ /**
+ * Stop a pairing flow whose attempt was abandoned, so the next attempt does not run beside it.
+ *
+ * The library's own cancel clears the in-page re-request interval and returns the page to QR mode.
+ * Best-effort in every direction: the method is absent on older builds, and it is a page evaluate
+ * against the page that just failed, so neither its absence nor its failure may surface here.
+ */
+ private async cancelAbandonedPairing(): Promise<void> {
+ const cancel = (this.client as unknown as { cancelPairingCode?: () => Promise<void> } | null)?.cancelPairingCode;
+ if (typeof cancel !== 'function') return;
+ try {
+ await cancel.call(this.client);
+ } catch (error) {
+ this.host.logger.debug('Could not cancel the abandoned pairing attempt', {
+ sessionId: this.host.config.sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
}
diff --git a/src/engine/adapters/wwebjs-pairing-code.spec.ts b/src/engine/adapters/wwebjs-pairing-code.spec.ts
index b63d1c6c2..d29168aac 100644
--- a/src/engine/adapters/wwebjs-pairing-code.spec.ts
+++ b/src/engine/adapters/wwebjs-pairing-code.spec.ts
@@ -16,14 +16,14 @@ import type { Client } from 'whatsapp-web.js';
* 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 {
+function makeLifecycle(requestPairingCode: jest.Mock, cancelPairingCode?: 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;
+ lc.client = { requestPairingCode, ...(cancelPairingCode ? { cancelPairingCode } : {}) } as unknown as Client;
return lc;
}
@@ -38,6 +38,39 @@ describe('requestPairingCode retries a mid-navigation page', () => {
expect(requestPairingCode).not.toHaveBeenCalled();
});
+ it('cancels the abandoned attempt before starting the next one', async () => {
+ // The race abandons the losing attempt without cancelling it, and the library's flow arms an
+ // interval that keeps re-requesting a code. Two flows would then compete over one device slot.
+ jest.useFakeTimers();
+ const requestPairingCode = jest
+ .fn()
+ .mockRejectedValueOnce(new Error('Execution context was destroyed, most likely because of a navigation.'))
+ .mockResolvedValueOnce('WXYZ1234');
+ const cancelPairingCode = jest.fn().mockResolvedValue(undefined);
+ const lc = makeLifecycle(requestPairingCode, cancelPairingCode);
+
+ const pending = lc.requestPairingCode('628111');
+ await jest.advanceTimersByTimeAsync(PAIRING_CODE_RETRY_DELAY_MS + 10);
+
+ await expect(pending).resolves.toBe('WXYZ1234');
+ expect(cancelPairingCode).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries even when the library offers no cancel, and when the cancel itself fails', async () => {
+ jest.useFakeTimers();
+ const failingCancel = jest.fn().mockRejectedValue(new Error('page is gone'));
+ const requestPairingCode = jest
+ .fn()
+ .mockRejectedValueOnce(new Error('Execution context was destroyed, most likely because of a navigation.'))
+ .mockResolvedValueOnce('WXYZ1234');
+ const lc = makeLifecycle(requestPairingCode, failingCancel);
+
+ const pending = lc.requestPairingCode('628111');
+ await jest.advanceTimersByTimeAsync(PAIRING_CODE_RETRY_DELAY_MS + 10);
+
+ await expect(pending).resolves.toBe('WXYZ1234');
+ });
+
it('retries a navigation-destroyed context and returns the code once the page reboots', async () => {
jest.useFakeTimers();
const requestPairingCode = jest