Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): keep a forward going past a live-page read error

Yudhi Armyndharis2626bc28bd20
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 3d7f9eaca..620cc78a5 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -183,6 +183,7 @@ export class WhatsAppWebJsAdapter implements IWhatsAppEngine {
logger: this.logger,
isPageTransportError: error => this.isPageTransportError(error),
reportIfPageTransportError: (error, context) => this.reportIfPageTransportError(error, context),
+ reportOnceGone: (error, context) => this.lifecycle.reportOnceGone(error, context),
ensureNotChannelRecipient: chatId => this.ensureNotChannelRecipient(chatId),
// The raw answer, `@lid` included: the send resolver addresses a migrated contact by it, while the
// public getNumberId reports the neutral phone id.
diff --git a/src/engine/adapters/wwebjs-client-teardown.spec.ts b/src/engine/adapters/wwebjs-client-teardown.spec.ts
index 7e63b80c9..fc5e63d25 100644
--- a/src/engine/adapters/wwebjs-client-teardown.spec.ts
+++ b/src/engine/adapters/wwebjs-client-teardown.spec.ts
@@ -386,6 +386,60 @@ describe('whatsapp-web.js operations that race a session teardown', () => {
expect(adapter.getStatus()).toBe(EngineStatus.READY);
});
+ // A page-side exception reaches Node as "Evaluation failed: ..." and can quote WhatsApp Web's own socket
+ // ("connection closed"), or a transport phrase of the caller's own making. With the page alive that is a
+ // failed read, not a death: the forward goes on as it did before the read reported anything.
+ it.each([
+ ['Evaluation failed: Error: connection closed'],
+ ['Evaluation failed: Error: Protocol error: target closed'],
+ ])('lets a forward go on when the destination read says "%s" and the page is alive', async message => {
+ const forward = jest.fn().mockResolvedValue(undefined);
+ const source = { fetchMessages: () => Promise.resolve([{ id: { _serialized: 'M1' }, forward }]) };
+ const destination = { fetchMessages: () => Promise.reject(new Error(message)) };
+ const { adapter } = readyAdapter({
+ pupPage: { isClosed: () => false },
+ pupBrowser: { isConnected: () => true },
+ getNumberId: () => Promise.resolve(found(CHAT)),
+ getChatById: (id: string) => Promise.resolve(id === '[email protected]' ? source : destination),
+ });
+ const onDisconnected = jest.fn();
+ (adapter as unknown as { callbacks: unknown }).callbacks = { onDisconnected };
+
+ await expect(adapter.forwardMessage('[email protected]', CHAT, 'M1')).resolves.toEqual({
+ id: '',
+ timestamp: expect.any(Number) as unknown,
+ });
+ expect(forward).toHaveBeenCalledTimes(1);
+ expect(onDisconnected).not.toHaveBeenCalled();
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ });
+
+ // Puppeteer rejects a call pending on a dying page a few milliseconds before it marks the page closed
+ // (measured with Chromium stopped by SIGTERM and a tab closed from outside), so the flags read alive at
+ // the moment the read fails.
+ it('still refuses a forward when the page reads gone only a moment after its destination read failed', async () => {
+ const forward = jest.fn();
+ const source = { fetchMessages: () => Promise.resolve([{ id: { _serialized: 'M1' }, forward }]) };
+ const destination = { fetchMessages: () => Promise.reject(closedTarget()) };
+ let closed = false;
+ const { adapter } = readyAdapter({
+ pupPage: { isClosed: () => closed },
+ pupBrowser: { isConnected: () => true },
+ getNumberId: () => Promise.resolve(found(CHAT)),
+ getChatById: (id: string) => Promise.resolve(id === '[email protected]' ? source : destination),
+ });
+ const onDisconnected = jest.fn();
+ (adapter as unknown as { callbacks: unknown }).callbacks = { onDisconnected };
+ setTimeout(() => (closed = true), 60);
+
+ const result = await outcomeOf(adapter.forwardMessage('[email protected]', CHAT, 'M1'));
+
+ expect(result).toEqual({ error: expect.any(EngineNotReadyError) as unknown });
+ expect(forward).not.toHaveBeenCalled();
+ expect(onDisconnected).toHaveBeenCalledTimes(1);
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ });
+
it('keeps a send that was already on the wire an outcome-unknown failure', async () => {
const onWire = gate();
const sendMessage = jest.fn(() =>
@@ -472,6 +526,7 @@ const DEATH_CASES: DeathCase[] = [
const source = { fetchMessages: () => Promise.resolve([{ id: { _serialized: 'M1' }, forward }]) };
return {
client: {
+ pupPage: { isClosed: () => true },
getNumberId: () => Promise.resolve(found(CHAT)),
getChatById: (id: string) => (id === '[email protected]' ? Promise.resolve(source) : Promise.reject(closedTarget())),
},
@@ -488,6 +543,8 @@ const DEATH_CASES: DeathCase[] = [
const destination = { fetchMessages: () => Promise.reject(closedTarget()) };
return {
client: {
+ pupPage: { isClosed: () => false },
+ pupBrowser: { isConnected: () => false },
getNumberId: () => Promise.resolve(found(CHAT)),
getChatById: (id: string) => Promise.resolve(id === '[email protected]' ? source : destination),
},
diff --git a/src/engine/adapters/wwebjs-host.ts b/src/engine/adapters/wwebjs-host.ts
index 6d5a90d6a..73a460816 100644
--- a/src/engine/adapters/wwebjs-host.ts
+++ b/src/engine/adapters/wwebjs-host.ts
@@ -24,6 +24,12 @@ export interface WwebjsEngineHost {
readonly logger: ReturnType<typeof createLogger>;
isPageTransportError(error: unknown): boolean;
reportIfPageTransportError(error: unknown, context: string): void;
+ /**
+ * For a best-effort read that carries on after a failure: reports a death only once puppeteer's page or
+ * browser reads gone (it is given a moment to), never on the error's text alone. Optional so a host built
+ * without it keeps the text-free behaviour of simply carrying on.
+ */
+ reportOnceGone?(error: unknown, context: string): Promise<void>;
ensureNotChannelRecipient(chatId: string): void;
getNumberId(number: string): Promise<string | null>;
capInboundMediaFor(
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index b0704c93a..c4f0756a8 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -796,6 +796,10 @@ export class WwebjsLifecycle {
this.host.getCallbacks().onDisconnected?.(reason);
}
+ /** How many times, and how far apart, {@link reportOnceGone} looks for puppeteer to mark a page gone. */
+ private static readonly PAGE_GONE_POLLS = 25;
+ private static readonly PAGE_GONE_POLL_MS = 20;
+
/**
* 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').
@@ -847,6 +851,38 @@ export class WwebjsLifecycle {
if (!this.isPageTransportError(error)) {
return;
}
+ this.reportDeath(error, context);
+ }
+
+ /**
+ * For a best-effort read that carries on after a failure, which must not take the session down on an
+ * error's text: a page-side exception can quote "connection closed" about WhatsApp Web's own socket while
+ * the page is fine. Puppeteer rejects a call pending on a dying page a few milliseconds BEFORE it marks
+ * the page closed or the browser disconnected (measured with Chromium stopped by SIGTERM and with a tab
+ * closed from outside; a killed browser already reads disconnected), so the page gets a short while to
+ * show it is gone. A page that still reads alive after that is not reported and the caller carries on.
+ */
+ async reportOnceGone(error: unknown, context: string): Promise<void> {
+ if (!this.isPageTransportError(error)) return;
+ // Counted in polls rather than elapsed time: every poll hands the event loop a turn, which is when
+ // puppeteer's close events are delivered, even if the process was starved for longer than the wait.
+ for (let polls = 0; polls < WwebjsLifecycle.PAGE_GONE_POLLS; polls++) {
+ if (this.status !== EngineStatus.READY || this.isPageGone()) break;
+ await new Promise(resolve => setTimeout(resolve, WwebjsLifecycle.PAGE_GONE_POLL_MS));
+ }
+ // Not READY any more means a death listener or a teardown got there first and owns the report.
+ if (this.status !== EngineStatus.READY) return;
+ if (!this.isPageGone()) {
+ this.host.logger.warn(`Page transport error during ${context} while the page is alive, not a death`, {
+ error: error instanceof Error ? error.message : String(error),
+ action: 'page_transport_error_page_alive',
+ });
+ return;
+ }
+ this.reportDeath(error, context);
+ }
+
+ private reportDeath(error: unknown, context: string): void {
// Inside the navigation re-inject window the same signatures ride a HEALING page: an in-flight
// evaluate killed by the navigation keeps its 'Protocol error' prefix (puppeteer only rewrites
// the shapes that END with a context-gone suffix), and a navigating page transiently detaches
@@ -870,6 +906,15 @@ export class WwebjsLifecycle {
this.handlePuppeteerDeath(`Page transport error during ${context}`);
}
+ /** Whether puppeteer itself reports the page closed or the browser disconnected (not an error's text). */
+ private isPageGone(): boolean {
+ const { pupBrowser, pupPage } = (this.client ?? {}) as unknown as {
+ pupBrowser?: { isConnected?: () => boolean };
+ pupPage?: { isClosed?: () => boolean };
+ };
+ return pupPage?.isClosed?.() === true || pupBrowser?.isConnected?.() === false;
+ }
+
markReadyFromClientInfo(): void {
if (
[EngineStatus.READY, EngineStatus.DISCONNECTED, EngineStatus.FAILED, EngineStatus.ACTION_REQUIRED].includes(
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index 9a98c4da6..c33f5ab9e 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -799,8 +799,10 @@ export class WwebjsMessaging {
};
} catch (error) {
// A page that died under the read is not a read that merely failed. Chromium stopped from
- // outside rejects this call before any death listener runs, so report it for the check below.
- this.host.reportIfPageTransportError(error, 'forwardMessage');
+ // outside rejects this call before any death listener runs, so report it for the check below,
+ // but only once the page itself reads gone: a live page whose exception merely says "connection
+ // closed" is a read that failed, and the forward goes on.
+ await this.host.reportOnceGone?.(error, 'forwardMessage');
this.host.logger.warn(`Could not read the destination chat before forwarding: ${String(error)}`);
}
// The read above is a page round trip a teardown can land in. Its failure only leaves the copy