Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): harden stability follow-ups — terminal 403, singleton cleanup, transport-error detection

Yudhi Armyndharise9294c5cbae1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9bf374d91..5ed7d9560 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Baileys engine, `connectionReplaced` (440) is now terminal instead of fighting the other instance,
duplicate close events no longer burn retry attempts, and a failed reconnect attempt no longer
fails the session.
+- Harden session stability further: the Baileys engine now treats `forbidden` (403, banned/blocked
+ account) as terminal instead of retrying forever; stale Chromium `SingletonLock`/`SingletonSocket`/
+ `SingletonCookie` files are removed before each whatsapp-web.js (re)launch so a previously
+ force-killed browser can never block startup; and page transport errors (`Protocol error`,
+ `Target closed`, detached frame, …) observed during send/query operations are now treated as an
+ immediate death signal, cutting dead-session detection from minutes to the first failed call.
## [0.9.0] - 2026-07-18
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 4a43cc8ec..f3d4ce80f 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -79,7 +79,7 @@ jest.mock('@whiskeysockets/baileys', () => ({
),
// Identity passthrough by default; individual tests may override to simulate unwrapping.
normalizeMessageContent: jest.fn((c: unknown) => c),
- DisconnectReason: { loggedOut: 401, restartRequired: 515, connectionReplaced: 440 },
+ DisconnectReason: { loggedOut: 401, forbidden: 403, restartRequired: 515, connectionReplaced: 440 },
proto: {
Message: {
ProtocolMessage: {
@@ -488,6 +488,30 @@ describe('BaileysAdapter reconnect policy — unlimited backoff (I4 hardening)',
}
});
+ it('403 forbidden is terminal: FAILED + onError, NO reconnect, auth NOT cleared', async () => {
+ const onError = jest.fn();
+ const adapter = await initWithRealTimers({ onError });
+ baileys().default.mockClear();
+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ try {
+ jest.useFakeTimers();
+
+ fakeSock.fire('connection.update', {
+ connection: 'close',
+ lastDisconnect: { error: { output: { statusCode: 403 } } },
+ });
+ await jest.runAllTimersAsync(); // would run any scheduled reconnect — none must be scheduled
+
+ expect(adapter.getStatus()).toBe(EngineStatus.FAILED);
+ expect(onError).toHaveBeenCalledTimes(1);
+ expect(onError).toHaveBeenCalledWith(expect.stringContaining('Account rejected by WhatsApp (403)'));
+ expect(baileys().default).not.toHaveBeenCalled(); // no reconnect — account is banned/blocked
+ expect(rmSpy).not.toHaveBeenCalled(); // auth survives — account-level refusal, not dead creds
+ } finally {
+ rmSpy.mockRestore();
+ }
+ });
+
it('a recoverable close after disconnect() (intentionalClose) does NOT schedule a reconnect', async () => {
const adapter = await initWithRealTimers({});
baileys().default.mockClear();
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 97ceba150..902effbeb 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -375,7 +375,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
}
if (statusCode === (this.lib?.DisconnectReason.connectionReplaced ?? 440)) {
- // Another live instance took over this account (whatsmeow StreamReplaced). Reconnecting
+ // Another live instance took over this account. Reconnecting
// would fight it — two instances endlessly replacing each other — so this is terminal:
// the operator stops the other instance, then starts this session again (onError = terminal
// + evict in the session service). Auth state is NOT cleared: the link itself is still valid.
@@ -386,8 +386,21 @@ export class BaileysAdapter implements IWhatsAppEngine {
return;
}
+ if (statusCode === (this.lib?.DisconnectReason.forbidden ?? 403)) {
+ // The account itself was rejected by WhatsApp (banned/blocked — an authorization-level
+ // refusal that must not be retried). Retrying forever is pointless and risks worsening
+ // the account's standing, so this is terminal like 440. Auth state is NOT cleared (unlike
+ // 401): this is an account-level refusal, not dead credentials — the operator keeps the auth
+ // files for inspection and can retry manually once the account issue is resolved.
+ this.setStatus(EngineStatus.FAILED);
+ this.callbacks.onError?.(
+ 'Account rejected by WhatsApp (403) — the number is likely banned or blocked; reconnecting will not help',
+ );
+ return;
+ }
+
// Every other close (408/411/428/500/503/515/undefined) is transient: reconnect with capped
- // backoff and NO attempt ceiling (whatsmeow/evolution-api style) — a long network outage must
+ // backoff and NO attempt ceiling — a long network outage must
// not kill the session. The counter resets on 'open' and via the stability window below.
// Do NOT fire onDisconnected here; this is a transient drop, not a terminal disconnect.
// connect() calls setStatus(INITIALIZING) which fires onStateChanged — that is the correct signal.
@@ -413,8 +426,8 @@ export class BaileysAdapter implements IWhatsAppEngine {
/**
* Schedule the next reconnect attempt with capped exponential backoff (1 s doubling up to a 60 s
* cap, plus up to 1 s jitter). Deliberately NO attempt ceiling: transient drops retry forever —
- * only loggedOut (401) and connectionReplaced (440) are terminal. A connect() failure inside the
- * attempt is just a failed attempt: warn and schedule the next one.
+ * only loggedOut (401), forbidden (403), and connectionReplaced (440) are terminal. A connect()
+ * failure inside the attempt is just a failed attempt: warn and schedule the next one.
*/
private scheduleReconnect(): void {
if (this.intentionalClose || this.reconnectTimer) {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 77a684d2e..ff3138374 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -1,4 +1,4 @@
-import { MessageMedia, WAState } from 'whatsapp-web.js';
+import { Client, MessageMedia, WAState } from 'whatsapp-web.js';
import { EventEmitter } from 'events';
import {
WhatsAppWebJsAdapter,
@@ -14,6 +14,7 @@ import {
} from './whatsapp-web-js.adapter';
import { getEffectiveWebVersionInfo, resolveWebVersionPin, __resetWebVersionCache } from '../wa-web-version';
import * as fs from 'fs';
+import * as path from 'path';
import * as qrcode from 'qrcode';
import { InternalServerErrorException, UnprocessableEntityException } from '@nestjs/common';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
@@ -2426,3 +2427,134 @@ describe('WhatsAppWebJsAdapter.probeLiveness (session watchdog probe)', () => {
}
});
});
+
+describe('WhatsAppWebJsAdapter stale Singleton cleanup (pre-launch)', () => {
+ const SESSION_ID = 'sess-singleton';
+ const newAdapter = (): WhatsAppWebJsAdapter =>
+ new WhatsAppWebJsAdapter({ sessionId: SESSION_ID, sessionDataPath: './data/sessions', puppeteer: {} });
+
+ let rmSpy: jest.SpyInstance;
+ let clientInitSpy: jest.SpyInstance;
+ let savedWebVersion: string | undefined;
+
+ beforeEach(() => {
+ // Keep initialize() offline: 'off' skips the wa-version registry fetch in resolveWebVersionPin.
+ savedWebVersion = process.env.WWEBJS_WEB_VERSION;
+ process.env.WWEBJS_WEB_VERSION = 'off';
+ rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ // Stub Client.prototype.initialize so the real wwebjs Client is built but no browser launches.
+ // (Structural cast: the wwebjs Client typings don't resolve under the lint project.)
+ clientInitSpy = jest
+ .spyOn(Client.prototype as unknown as { initialize: () => Promise<void> }, 'initialize')
+ .mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ rmSpy.mockRestore();
+ clientInitSpy.mockRestore();
+ if (savedWebVersion === undefined) {
+ delete process.env.WWEBJS_WEB_VERSION;
+ } else {
+ process.env.WWEBJS_WEB_VERSION = savedWebVersion;
+ }
+ });
+
+ it('removes the three Singleton files from the LocalAuth profile dir right before client.initialize()', async () => {
+ const order: string[] = [];
+ rmSpy.mockImplementation(() => {
+ order.push('rm');
+ return Promise.resolve(undefined);
+ });
+ clientInitSpy.mockImplementation(() => {
+ order.push('client.initialize');
+ return Promise.resolve(undefined);
+ });
+
+ await newAdapter().initialize({});
+
+ // Same dir LocalAuth uses as userDataDir: <resolved dataPath>/session-<clientId>.
+ const profileDir = path.join(path.resolve('./data/sessions'), `session-${SESSION_ID}`);
+ expect(rmSpy).toHaveBeenCalledTimes(3);
+ expect(rmSpy).toHaveBeenCalledWith(path.join(profileDir, 'SingletonLock'), { force: true });
+ expect(rmSpy).toHaveBeenCalledWith(path.join(profileDir, 'SingletonSocket'), { force: true });
+ expect(rmSpy).toHaveBeenCalledWith(path.join(profileDir, 'SingletonCookie'), { force: true });
+ expect(clientInitSpy).toHaveBeenCalledTimes(1);
+ expect(order).toEqual(['rm', 'rm', 'rm', 'client.initialize']);
+ });
+
+ it('still initializes when the Singleton files cannot be removed (best-effort, never fails the start)', async () => {
+ rmSpy.mockRejectedValue(new Error('EPERM: operation not permitted'));
+
+ await expect(newAdapter().initialize({})).resolves.toBeUndefined();
+
+ expect(rmSpy).toHaveBeenCalledTimes(3); // all three attempted even though each failed
+ expect(clientInitSpy).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-path, wwebjs #5728)', () => {
+ const readyAdapter = (client: unknown): { adapter: WhatsAppWebJsAdapter; onDisconnected: jest.Mock } => {
+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });
+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;
+ (adapter as unknown as { client: unknown }).client = client;
+ const onDisconnected = jest.fn();
+ (adapter as unknown as { callbacks: unknown }).callbacks = { onDisconnected };
+ return { adapter, onDisconnected };
+ };
+
+ // A wedged page fires no events while still reporting CONNECTED, so a failed operation carrying a
+ // transport-death signature is the earliest signal — it must route through the disconnect path.
+ it.each([
+ 'Protocol error: Target closed',
+ 'Protocol error (Runtime.callFunctionOn): Target closed.',
+ 'TargetClosedError: page closed',
+ 'Attempted to use detached Frame',
+ 'Session closed',
+ 'Connection closed',
+ ])('reports a failed send carrying "%s" as a disconnect', async message => {
+ const sendMessage = jest.fn().mockRejectedValue(new Error(message));
+ const { adapter, onDisconnected } = readyAdapter({ sendMessage });
+
+ await expect(adapter.sendTextMessage('[email protected]', 'hi')).rejects.toThrow(message);
+
+ expect(onDisconnected).toHaveBeenCalledTimes(1);
+ expect(onDisconnected).toHaveBeenCalledWith('Page transport error during sendMessage');
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ });
+
+ // Ordinary operation failures must NOT trip the death path — the error only propagates to the caller.
+ it.each(['WhatsApp rate limit', 'Evaluation failed: TypeError: x is not a function'])(
+ 'does not report an ordinary send failure (%s) as a disconnect',
+ async message => {
+ const sendMessage = jest.fn().mockRejectedValue(new Error(message));
+ const { adapter, onDisconnected } = readyAdapter({ sendMessage });
+
+ await expect(adapter.sendTextMessage('[email protected]', 'hi')).rejects.toThrow(message);
+
+ expect(onDisconnected).not.toHaveBeenCalled();
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ },
+ );
+
+ it('detects a transport error from a getter too (getContacts)', async () => {
+ const getContacts = jest.fn().mockRejectedValue(new Error('Protocol error: Target closed'));
+ const { adapter, onDisconnected } = readyAdapter({ getContacts });
+
+ await expect(adapter.getContacts()).rejects.toThrow('Protocol error: Target closed');
+
+ expect(onDisconnected).toHaveBeenCalledTimes(1);
+ expect(onDisconnected).toHaveBeenCalledWith('Page transport error during getContacts');
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ });
+
+ it('reports nothing when the failure happens during an intentional teardown', async () => {
+ const sendMessage = jest.fn().mockRejectedValue(new Error('Protocol error: Target closed'));
+ const { adapter, onDisconnected } = readyAdapter({ sendMessage });
+ (adapter as unknown as { tearingDown: boolean }).tearingDown = true;
+
+ await expect(adapter.sendTextMessage('[email protected]', 'hi')).rejects.toThrow('Protocol error: Target closed');
+
+ expect(onDisconnected).not.toHaveBeenCalled();
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 8d76dbd73..db3183cf7 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -458,6 +458,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.setStatus(EngineStatus.DISCONNECTED);
return;
}
+ // Clear stale Chromium Singleton* files left by a hard kill before launching — see
+ // removeStaleSingletonFiles. This runs only at engine (re)start, never while
+ // the browser is alive, so it cannot pull the files out from under a running Chromium.
+ await this.removeStaleSingletonFiles();
await this.client.initialize();
// whatsapp-web.js 1.34.x never observes the Chromium process/page it drives, so a crashed
// browser leaves the client looking READY forever ("silent death"). Attach death listeners
@@ -769,6 +773,32 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.callbacks.onDisconnected?.(reason);
}
+ /**
+ * Error-message signatures of a dead page/transport: Puppeteer raises these when the browser
+ * process, the renderer, or the CDP connection is gone (e.g. 'Protocol error: Target closed').
+ */
+ private static readonly PAGE_TRANSPORT_ERROR_PATTERN =
+ /protocol error|target closed|targetclosederror|detached frame|session closed|connection closed/i;
+
+ /**
+ * Report a failed client/page operation as a session death when the error matches
+ * PAGE_TRANSPORT_ERROR_PATTERN. A wedged page can fire NO events while still reporting CONNECTED
+ * (whatsapp-web.js #5728), so the watchdog takes minutes to notice — an operation failing with one
+ * of these errors is a much earlier death signal. Detection
+ * only: the error itself still propagates to the caller exactly as before, and
+ * handlePuppeteerDeath's guard makes this safe during teardown and against double-reporting.
+ */
+ private reportIfPageTransportError(error: unknown, context: string): void {
+ const message = error instanceof Error ? error.message : String(error);
+ if (!WhatsAppWebJsAdapter.PAGE_TRANSPORT_ERROR_PATTERN.test(message)) {
+ return;
+ }
+ this.logger.warn(`Page transport error during ${context} — treating the session as dead`, {
+ error: message,
+ });
+ this.handlePuppeteerDeath(`Page transport error during ${context}`);
+ }
+
private markReadyFromClientInfo(): void {
if ([EngineStatus.READY, EngineStatus.DISCONNECTED, EngineStatus.FAILED].includes(this.status)) return;
this.clearReadyReconcile();
@@ -881,6 +911,24 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
});
}
+ /**
+ * Remove Chromium's SingletonLock/SingletonSocket/SingletonCookie from the LocalAuth profile dir
+ * (same dir clearLocalAuth removes) before the browser launches. A hard-killed Chromium
+ * (SIGKILL/crash) leaves them behind, and on some setups (e.g. Docker PID reuse) the stale files
+ * block the next launch unless they are cleared first. Best-effort: a removal
+ * failure only logs at debug and never fails the start.
+ */
+ private async removeStaleSingletonFiles(): Promise<void> {
+ const profileDir = path.join(path.resolve(this.config.sessionDataPath), `session-${this.config.sessionId}`);
+ for (const name of ['SingletonLock', 'SingletonSocket', 'SingletonCookie']) {
+ try {
+ await fs.promises.rm(path.join(profileDir, name), { force: true });
+ } catch (error) {
+ this.logger.debug(`Could not remove stale ${name} from ${profileDir}`, { error: String(error) });
+ }
+ }
+ }
+
private async isClientRuntimeReady(): Promise<boolean> {
if (!this.client) return false;
if ((await this.client.getState()) !== WAState.CONNECTED) return false;
@@ -1109,6 +1157,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
try {
return await send(to);
} catch (err) {
+ // A transport-level failure means the page/browser is gone — report it as a death signal.
+ // No-op for ordinary send errors; the retry/throw behavior below is unchanged.
+ this.reportIfPageTransportError(err, 'sendMessage');
if (!chatId.endsWith('@c.us') || !isNoLidForUserError(err)) {
throw err;
}
@@ -1185,16 +1236,21 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
async getContacts(): Promise<Contact[]> {
this.ensureReady();
- const contacts = await this.client!.getContacts();
-
- return contacts.map(c => ({
- id: c.id._serialized,
- name: c.name || undefined,
- pushName: c.pushname || undefined,
- number: c.number,
- isMyContact: c.isMyContact,
- isBlocked: c.isBlocked,
- }));
+ try {
+ const contacts = await this.client!.getContacts();
+
+ return contacts.map(c => ({
+ id: c.id._serialized,
+ name: c.name || undefined,
+ pushName: c.pushname || undefined,
+ number: c.number,
+ isMyContact: c.isMyContact,
+ isBlocked: c.isBlocked,
+ }));
+ } catch (error) {
+ this.reportIfPageTransportError(error, 'getContacts');
+ throw error;
+ }
}
async getContactById(contactId: string): Promise<Contact | null> {
@@ -1217,8 +1273,13 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
async getNumberId(number: string): Promise<string | null> {
this.ensureReady();
- const numberId = await this.client!.getNumberId(number);
- return numberId?._serialized ?? null;
+ try {
+ const numberId = await this.client!.getNumberId(number);
+ return numberId?._serialized ?? null;
+ } catch (error) {
+ this.reportIfPageTransportError(error, 'getNumberId');
+ throw error;
+ }
}
async checkNumberExists(number: string): Promise<boolean> {
@@ -1244,28 +1305,33 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
async getGroups(): Promise<Group[]> {
this.ensureReady();
- const chats = await this.client!.getChats();
-
- // Filter only group chats
- const groups = chats.filter(chat => chat.isGroup);
-
- // List path: read linkedParentJID synchronously from whatever metadata getChats()
- // already loaded. We deliberately do NOT fall back to getChatById per group here —
- // that would be an N+1 round-trip across every group on every list call. Groups
- // whose metadata isn't loaded report null; the single-group endpoint (getGroupInfo,
- // which loads full metadata via getChatById) is the authoritative source.
- return groups.map(g => {
- const groupChat = g as unknown as GroupChat;
- return {
- id: g.id._serialized,
- name: g.name,
- participantsCount: groupChat.participants?.length,
- isAdmin: groupChat.participants?.some(
- p => p.isAdmin && p.id._serialized === this.client?.info?.wid?._serialized,
- ),
- linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),
- };
- });
+ try {
+ const chats = await this.client!.getChats();
+
+ // Filter only group chats
+ const groups = chats.filter(chat => chat.isGroup);
+
+ // List path: read linkedParentJID synchronously from whatever metadata getChats()
+ // already loaded. We deliberately do NOT fall back to getChatById per group here —
+ // that would be an N+1 round-trip across every group on every list call. Groups
+ // whose metadata isn't loaded report null; the single-group endpoint (getGroupInfo,
+ // which loads full metadata via getChatById) is the authoritative source.
+ return groups.map(g => {
+ const groupChat = g as unknown as GroupChat;
+ return {
+ id: g.id._serialized,
+ name: g.name,
+ participantsCount: groupChat.participants?.length,
+ isAdmin: groupChat.participants?.some(
+ p => p.isAdmin && p.id._serialized === this.client?.info?.wid?._serialized,
+ ),
+ linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),
+ };
+ });
+ } catch (error) {
+ this.reportIfPageTransportError(error, 'getGroups');
+ throw error;
+ }
}
// ============= Phase 3: Extended Messaging =============
@@ -1345,65 +1411,78 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
async replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {
this.ensureReady();
- // Find the message to quote
- const chat = await this.client!.getChatById(chatId);
- const messages = await chat.fetchMessages({ limit: 100 });
- const quotedMsg = messages.find(m => m.id._serialized === quotedMsgId);
+ try {
+ // Find the message to quote
+ const chat = await this.client!.getChatById(chatId);
+ const messages = await chat.fetchMessages({ limit: 100 });
+ const quotedMsg = messages.find(m => m.id._serialized === quotedMsgId);
- if (!quotedMsg) {
- throw new MessageNotFoundError(quotedMsgId);
- }
+ if (!quotedMsg) {
+ throw new MessageNotFoundError(quotedMsgId);
+ }
- // Reply's send leg hits the same `No LID for user` path as a normal send for a migrated contact,
- // so route it through sendResolved (resolve @c.us->@lid, cache, self-heal). reply(content, chatId)
- // accepts an explicit target (#583 R1).
- const msg = await this.sendResolved(chatId, to => quotedMsg.reply(text, to));
- return this.toMessageResult(msg);
+ // Reply's send leg hits the same `No LID for user` path as a normal send for a migrated contact,
+ // so route it through sendResolved (resolve @c.us->@lid, cache, self-heal). reply(content, chatId)
+ // accepts an explicit target (#583 R1).
+ const msg = await this.sendResolved(chatId, to => quotedMsg.reply(text, to));
+ return this.toMessageResult(msg);
+ } catch (error) {
+ this.reportIfPageTransportError(error, 'replyToMessage');
+ throw error;
+ }
}
async forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {
this.ensureReady();
- const chat = await this.client!.getChatById(fromChatId);
- const messages = await chat.fetchMessages({ limit: 100 });
- const msgToForward = messages.find(m => m.id._serialized === messageId);
+ try {
+ const chat = await this.client!.getChatById(fromChatId);
+ const messages = await chat.fetchMessages({ limit: 100 });
+ const msgToForward = messages.find(m => m.id._serialized === messageId);
- if (!msgToForward) {
- throw new MessageNotFoundError(messageId);
- }
+ if (!msgToForward) {
+ throw new MessageNotFoundError(messageId);
+ }
- // The forward's send leg fails with `No LID for user` for a LID-migrated destination, so resolve
- // it (and self-heal a stale mapping) via sendResolved. Capture the id actually sent to so the
- // id-recovery below reads back from the SAME (resolved) chat, not the raw @c.us (#583 R1).
- let resolvedTo = toChatId;
- await this.sendResolved(toChatId, to => {
- resolvedTo = to;
- return msgToForward.forward(to);
- });
+ // The forward's send leg fails with `No LID for user` for a LID-migrated destination, so resolve
+ // it (and self-heal a stale mapping) via sendResolved. Capture the id actually sent to so the
+ // id-recovery below reads back from the SAME (resolved) chat, not the raw @c.us (#583 R1).
+ let resolvedTo = toChatId;
+ await this.sendResolved(toChatId, to => {
+ resolvedTo = to;
+ return msgToForward.forward(to);
+ });
- // whatsapp-web.js's forward() returns void, so BEST-EFFORT recover the REAL id of the sent copy by
- // reading it back from the destination chat (the most recent outgoing message). The delivery-ack
- // matcher keys on this id, so a synthetic one would leave the forward stuck at SENT; Baileys already
- // returns the real id. The forward already succeeded here, so recovery must NEVER fail the operation.
- // When the copy can't be identified we return an explicit-unknown id (empty): message.service then
- // leaves the row's waMessageId unset so no ack can mis-match it — unlike a synthetic or source id,
- // which could cross-drive another row's delivery status. Concurrent forwards to the same chat may
- // mis-identify the copy — acceptable for delivery-status accuracy.
- try {
- const destChat = await this.client!.getChatById(resolvedTo);
- const sentByMe = (await destChat?.fetchMessages({ limit: 5, fromMe: true })) ?? [];
- let sent: (typeof sentByMe)[number] | undefined;
- for (const m of sentByMe) {
- if (!sent || m.timestamp > sent.timestamp) {
- sent = m;
+ // whatsapp-web.js's forward() returns void, so BEST-EFFORT recover the REAL id of the sent copy by
+ // reading it back from the destination chat (the most recent outgoing message). The delivery-ack
+ // matcher keys on this id, so a synthetic one would leave the forward stuck at SENT; Baileys already
+ // returns the real id. The forward already succeeded here, so recovery must NEVER fail the operation.
+ // When the copy can't be identified we return an explicit-unknown id (empty): message.service then
+ // leaves the row's waMessageId unset so no ack can mis-match it — unlike a synthetic or source id,
+ // which could cross-drive another row's delivery status. Concurrent forwards to the same chat may
+ // mis-identify the copy — acceptable for delivery-status accuracy.
+ try {
+ const destChat = await this.client!.getChatById(resolvedTo);
+ const sentByMe = (await destChat?.fetchMessages({ limit: 5, fromMe: true })) ?? [];
+ let sent: (typeof sentByMe)[number] | undefined;
+ for (const m of sentByMe) {
+ if (!sent || m.timestamp > sent.timestamp) {
+ sent = m;
+ }
}
+ if (sent) {
+ return this.toMessageResult(sent);
+ }
+ } catch (error) {
+ // Still surface a dead page even though the send itself succeeded (detection only; the
+ // forward's best-effort recovery contract is unchanged).
+ this.reportIfPageTransportError(error, 'forwardMessage');
+ this.logger.warn(`Forward succeeded but recovering the sent message id failed: ${String(error)}`);
}
- if (sent) {
- return this.toMessageResult(sent);
- }
+ return { id: '', timestamp: Math.floor(Date.now() / 1000) };
} catch (error) {
- this.logger.warn(`Forward succeeded but recovering the sent message id failed: ${String(error)}`);
+ this.reportIfPageTransportError(error, 'forwardMessage');
+ throw error;
}
- return { id: '', timestamp: Math.floor(Date.now() / 1000) };
}
// ============= Phase 3: Group Management =============
@@ -1538,17 +1617,22 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// Reactions (Phase 3)
async reactToMessage(chatId: string, messageId: string, emoji: string): Promise<void> {
this.ensureReady();
- // NOTE: do NOT resolve chatId to @lid here — whatsapp-web.js reacts using the found message's own
- // id, not this chatId, so LID-resolving the lookup gives no send benefit and would miss a message
- // stored under the pre-migration @c.us chat (#583 R1 review).
- const chat = await this.client!.getChatById(chatId);
- const messages = await chat.fetchMessages({ limit: 100 });
- const message = messages.find(m => m.id._serialized === messageId);
- if (!message) {
- throw new MessageNotFoundError(messageId, chatId);
+ try {
+ // NOTE: do NOT resolve chatId to @lid here — whatsapp-web.js reacts using the found message's own
+ // id, not this chatId, so LID-resolving the lookup gives no send benefit and would miss a message
+ // stored under the pre-migration @c.us chat (#583 R1 review).
+ const chat = await this.client!.getChatById(chatId);
+ const messages = await chat.fetchMessages({ limit: 100 });
+ const message = messages.find(m => m.id._serialized === messageId);
+ if (!message) {
+ throw new MessageNotFoundError(messageId, chatId);
+ }
+ await (message as MessageWithReactions).react(emoji);
+ this.logger.log(`Reacted to message ${messageId} with ${emoji || '(removed)'}`);
+ } catch (error) {
+ this.reportIfPageTransportError(error, 'reactToMessage');
+ throw error;
}
- await (message as MessageWithReactions).react(emoji);
- this.logger.log(`Reacted to message ${messageId} with ${emoji || '(removed)'}`);
}
async getMessageReactions(chatId: string, messageId: string): Promise<MessageReaction[]> {
@@ -1816,6 +1900,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
const url = await this.client!.getProfilePicUrl(contactId);
return url || null;
} catch (error) {
+ this.reportIfPageTransportError(error, 'getProfilePicture');
this.logger.warn(`Failed to get profile picture for ${contactId}: ${String(error)}`);
return null;
}