Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwjs): drop the pairing cancel and describe the call hook correctly

Yudhi Armyndharis063541273460
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bb12ce0c5..fefd1487e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,7 +42,6 @@ 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.
- `GET /api/sessions/:sessionId/contacts/:contactId` answers with the saved contact when the same person occupies two store entries, one keyed by LID and one by phone number. Only one of the two carries the saved name, and the lookup returned whichever it reached first, so a saved contact could answer with no name and `isMyContact: false`.
@@ -56,7 +55,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- An ingress route can declare `dedupOn: "body"` to key provider retries on the raw body instead of the delivery-id header. A provider that mints a fresh delivery id on every retry attempt, as supabase/auth does inside its hook retry loop, was never deduplicated when an ack was lost, so the contact received the message twice; routes that do not declare it keep the header ([#1641](https://github.com/rmyndharis/OpenWA/issues/1641)).
- Baileys sessions record a message the account sent from its phone while the gateway was down, and dispatch `message.sent` for it, as they already did for one sent while the gateway was online. The offline replay carried the same `append` tag as the library's echo of an API send, which the upsert handler dropped wholesale; it now skips only the ids this session sent itself, and the phone's reactions, edits and revokes from that window are replayed the same way ([#1667](https://github.com/rmyndharis/OpenWA/issues/1667)).
- Baileys sessions no longer drop the inbound messages WhatsApp queued while they were down. The offline replay is tagged `append`, which the upsert handler treated as history and skipped for anything older than the reconnect, so every message sent during an outage was never stored and never dispatched ([#1660](https://github.com/rmyndharis/OpenWA/issues/1660)). Thanks @fransarni for the report.
-- A whatsapp-web.js session that comes up without its page-side call hook says so in the log instead of silently never reporting an incoming call. The hook is installed part-way through the same page evaluate as the message listeners, which run before it, so the session stays healthy for messages either way ([#1655](https://github.com/rmyndharis/OpenWA/issues/1655)).
+- A whatsapp-web.js session that comes up without its page-side call hook says so in the log instead of silently never reporting an incoming call. The library installs the hook only when the page exposes the call collection it expects, so a WhatsApp Web build that moves that collection leaves calls undetected while messages keep working. The check is skipped on an install whose whatsapp-web.js patches were not applied, where a session can reach ready before the hook is installed and the warning would be false ([#1655](https://github.com/rmyndharis/OpenWA/issues/1655)).
- Stopping, unlinking or force-killing a session announces `session.status: disconnected` after the engine is released, not while it is still tearing down, so a dashboard tab or a webhook consumer no longer learns the session is down in the one moment the API still reports its engine as loaded. On whatsapp-web.js that window lasted as long as Chromium took to close, and left an open QR modal on a dead code with the started actions still offered ([#1649](https://github.com/rmyndharis/OpenWA/issues/1649)).
- The dashboard blanks a session's displayed QR code as soon as the session disconnects, so a code minted by a connection that is gone is never left on screen to be scanned ([#1649](https://github.com/rmyndharis/OpenWA/issues/1649)).
- A pairing-code request whose retry budget runs out on a reloading WhatsApp Web page answers `503` instead of `500`, so a client can tell a retryable transport failure from a broken gateway ([#1654](https://github.com/rmyndharis/OpenWA/issues/1654)).
diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsx
index 7fae3f534..bf864fd8d 100644
--- a/dashboard/src/components/chats/ChatThread.tsx
+++ b/dashboard/src/components/chats/ChatThread.tsx
@@ -78,9 +78,10 @@ function ChatThread({
// row reads as answered (WhatsApp treats a prompt as single-choice once answered).
//
// Client-side and per-visit only: this is reset when the active chat changes, and a reload starts
- // it empty, so an answered prompt becomes clickable again. The engine is the real gate, and a
- // second click is a second reply to the same prompt, which WhatsApp accepts; persisting the
- // answered state belongs with the message rather than in this component.
+ // it empty, so an answered prompt becomes clickable again. Nothing below this component refuses a
+ // second answer, and WhatsApp accepts it as another reply to the same prompt, so the flag is a
+ // courtesy against a double click rather than a guarantee; making it durable means persisting the
+ // answered state with the message, not widening this state.
const [buttonClick, setButtonClick] = useState<
Record<string, { loadingId?: string; done?: boolean; selectedId?: string }>
>({});
diff --git a/src/engine/adapters/wwebjs-call-hook-check.spec.ts b/src/engine/adapters/wwebjs-call-hook-check.spec.ts
index b0f102a80..6d1ecbd83 100644
--- a/src/engine/adapters/wwebjs-call-hook-check.spec.ts
+++ b/src/engine/adapters/wwebjs-call-hook-check.spec.ts
@@ -2,9 +2,10 @@ import { reportMissingCallHook } from './wwebjs-call-hook-check';
/**
* whatsapp-web.js detects an incoming call by patching ONE page function: the call collection's
- * internal `Map.set`. It installs that patch in the same `evaluate` as the message listeners, with
- * no try/catch, so anything that throws earlier in that evaluate leaves messages working and calls
- * undetectable, with nothing in the log to say so. This check turns that silence into a warning.
+ * internal `Map.set`. It installs that patch only when the page exposes a call collection shaped the
+ * way it expects, so a WhatsApp Web build that moves or renames that collection leaves messages
+ * working and calls undetectable, with nothing in the log to say so. This check turns that silence
+ * into a warning.
*/
describe('reportMissingCallHook', () => {
const makeLogger = (): { warn: jest.Mock; debug: jest.Mock } => ({ warn: jest.fn(), debug: jest.fn() });
diff --git a/src/engine/adapters/wwebjs-call-hook-check.ts b/src/engine/adapters/wwebjs-call-hook-check.ts
index 2e4e21604..29d1c7f4f 100644
--- a/src/engine/adapters/wwebjs-call-hook-check.ts
+++ b/src/engine/adapters/wwebjs-call-hook-check.ts
@@ -33,11 +33,13 @@ function readCallHookState(): boolean | null {
/**
* Warn when a ready session's page carries no call hook.
*
- * whatsapp-web.js installs the call hook part-way through the same `evaluate` as its message
- * listeners, and that evaluate has no `try`/`catch`: a module that stops resolving before it leaves
- * the message bridge registered and the call hook silently absent. The session then looks completely
- * healthy, keeps delivering messages, and never reports a single incoming call. Operators have no way to see
- * that from the outside, so say it in the log.
+ * whatsapp-web.js installs the call hook inside a conditional, part-way through the `evaluate` that
+ * registers its listeners: it patches the page's call collection only when the page exposes one
+ * shaped the way it expects. A WhatsApp Web build that moves or renames that collection skips the
+ * hook while the rest of the evaluate completes, so the session looks completely healthy, keeps
+ * delivering messages, and never reports a single incoming call. Operators have no way to see that
+ * from the outside, so say it in the log. (A stall inside the evaluate is not this case: the inbound
+ * message bridge is registered after the call hook, so it would stop message delivery too.)
*
* Deliberately advisory: it never changes the session's status. Detection is the only thing lost,
* and a false alarm on an inconclusive read would send operators after a problem they do not have.
diff --git a/src/engine/adapters/wwebjs-call-hook-gate.spec.ts b/src/engine/adapters/wwebjs-call-hook-gate.spec.ts
new file mode 100644
index 000000000..830a6f429
--- /dev/null
+++ b/src/engine/adapters/wwebjs-call-hook-gate.spec.ts
@@ -0,0 +1,65 @@
+import { EngineStatus } from '../interfaces/whatsapp-engine.interface';
+import { WwebjsLifecycle, type WwebjsLifecycleHost } from './wwebjs-lifecycle';
+import { unappliedPatches } from './engine-patch-status';
+import { reportMissingCallHook } from './wwebjs-call-hook-check';
+import type { Client } from 'whatsapp-web.js';
+
+jest.mock('./engine-patch-status', () => ({
+ unappliedPatches: jest.fn().mockReturnValue([]),
+ unappliedPatchesMessage: jest.fn().mockReturnValue(''),
+}));
+jest.mock('./wwebjs-call-hook-check', () => ({ reportMissingCallHook: jest.fn().mockResolvedValue(undefined) }));
+
+const patches = unappliedPatches as jest.Mock;
+const report = reportMissingCallHook as jest.Mock;
+
+/**
+ * The call-hook diagnostic is only meaningful once the page evaluate that installs the hook has
+ * finished. The ready-sync patch is what guarantees that: without it a session can be promoted to
+ * READY while the attach is still in flight, so the probe would read a hook that has simply not been
+ * installed YET and warn about a fault that does not exist.
+ */
+function makeLifecycle(): WwebjsLifecycle {
+ const host = {
+ logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
+ config: { sessionId: 'sess', sessionDataPath: './data' },
+ clearReadyReconcile: jest.fn(),
+ startOnboardingWatcher: jest.fn(),
+ emitState: jest.fn(),
+ getCallbacks: () => ({}),
+ } as unknown as WwebjsLifecycleHost;
+ const lc = new WwebjsLifecycle(host);
+ lc.status = EngineStatus.INITIALIZING;
+ lc.client = { info: { wid: { user: '628111' }, pushname: 'Me' } } as unknown as Client;
+ return lc;
+}
+
+describe('the call-hook diagnostic is gated on the ready-sync patch', () => {
+ beforeEach(() => {
+ patches.mockReset().mockReturnValue([]);
+ report.mockReset().mockResolvedValue(undefined);
+ });
+
+ it('runs the probe on a tree where the patch is applied', () => {
+ const lc = makeLifecycle();
+ lc.markReadyFromClientInfo();
+ expect(lc.status).toBe(EngineStatus.READY);
+ expect(report).toHaveBeenCalledTimes(1);
+ });
+
+ it('skips the probe when the ready-sync patch is missing', () => {
+ patches.mockReturnValue(['patch-wwebjs-ready-sync']);
+ const lc = makeLifecycle();
+ lc.markReadyFromClientInfo();
+ expect(lc.status).toBe(EngineStatus.READY); // the promotion itself is never affected
+ expect(report).not.toHaveBeenCalled();
+ });
+
+ it('still runs the probe when some other whatsapp-web.js patch is missing', () => {
+ // Only the patch that decides WHEN ready fires can make the probe lie; an unrelated one does not.
+ patches.mockReturnValue(['patch-wwebjs-media-id']);
+ const lc = makeLifecycle();
+ lc.markReadyFromClientInfo();
+ expect(report).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index e6fd38548..1696328e5 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -788,13 +788,15 @@ export class WwebjsLifecycle {
// gets the companion unlinked (~5m later → disconnected: LOGOUT, #982). Dismiss it best-effort
// and fall back to ACTION_REQUIRED. Started after READY so a non-ready session never arms it.
this.host.startOnboardingWatcher();
- // whatsapp-web.js installs its incoming-call hook part-way through the same page evaluate that
- // registers the message listeners, and that evaluate has no try/catch: a module that stops
- // resolving before it leaves the message bridge live and the call hook absent (and takes the
- // chat listeners registered after it as well).
- // The session then looks healthy, keeps delivering messages, and reports no call at all. Warn
- // once per ready rather than leaving that silent; nothing else changes, since only detection is
- // lost. Fire-and-forget: a diagnostic must never delay or fail the promotion to READY.
+ // whatsapp-web.js installs its incoming-call hook inside a conditional, part-way through the
+ // page evaluate that registers its listeners: it patches the call collection only when the page
+ // exposes one shaped the way it expects. A WhatsApp Web build that moves or renames that
+ // collection skips the hook while the rest of the evaluate completes, so the session looks
+ // healthy, keeps delivering messages, and reports no call at all. (A stall inside that evaluate
+ // is a different, noisier shape: the inbound message bridge is registered AFTER the call hook,
+ // so it would take message delivery with it.) Warn once per ready rather than leaving the quiet
+ // case silent; nothing else changes, since only detection is lost. Fire-and-forget: a
+ // diagnostic must never delay or fail the promotion to READY.
//
// Skipped on a tree missing the ready-sync patch: without it the session can reach READY while
// that same evaluate is still running, so the probe would read a page whose hook simply has not
@@ -1079,13 +1081,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();
+ // Nothing cancels the abandoned attempt, and nothing needs to. The library's own
+ // requestPairingCode clears the in-page re-request interval as the first act of its
+ // evaluate, so the next attempt stops the previous flow itself. Its `cancelPairingCode`
+ // would on top of that return the page to QR mode, which is the opposite of what a retry
+ // wants, and it is an unbounded page evaluate against the page that is already unwell, so
+ // awaiting it would add a full Puppeteer protocol timeout to each gap. What the abandoned
+ // flow does reach is the library's own CODE_RECEIVED event, which nothing here listens to.
await new Promise<void>(resolve => {
const t = setTimeout(resolve, PAIRING_CODE_RETRY_DELAY_MS);
t.unref?.();
@@ -1110,24 +1112,4 @@ 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 d29168aac..b63d1c6c2 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, cancelPairingCode?: jest.Mock): WwebjsLifecycle {
+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, ...(cancelPairingCode ? { cancelPairingCode } : {}) } as unknown as Client;
+ lc.client = { requestPairingCode } as unknown as Client;
return lc;
}
@@ -38,39 +38,6 @@ 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