Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): report a dead page from the five boolean chat operations

Yudhi Armyndharis5aa1a3d43d24
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 816388658..8b9b6d0f9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- Five whatsapp-web.js chat operations — mark-as-read, clear, archive, mark-unread and delete — no longer report a dead browser as a refusal. Each caught every error and resolved `false`, so the caller got `200 {"success": false}` ("WhatsApp declined a valid request") while the session's page was actually dead, and retried against it instead of receiving the documented 503. The early death signal was lost too, so the session kept reporting READY until the slower watchdog noticed. They now split transport failure out into `EngineTransportError` and report it, exactly as `getChats` and the other sibling reads in the same adapter already did. An ordinary page-side refusal still resolves `false`, unchanged.
+
- The cross-node takeover sweep no longer adopts sessions while the process is shutting down. `onModuleDestroy` cleared the interval, which stops the next sweep but does nothing about one already running — it is neither aborted nor awaited, and nothing on the start path consulted a shutting-down signal. On a rolling restart a sweep mid-flight could construct and register an engine after the shutdown path had emptied the registry, and claim the ownership lease for a process about to exit, pinning that session to a dead node until the lease lapsed. The signal is re-checked per adoption, because each one costs a browser launch and the loop spans much of the sweep interval.
- `GET /infra/storage/export` now enumerates the whole store. It listed with `listFiles()`, which stops at `STORAGE_LIST_MAX_FILES` and returns without logging or throwing, so an operator following the documented local→S3 migration — export, repoint `STORAGE_TYPE`, import — silently left media behind on the backend they were about to decommission, and the `files/count` pre-check was truncated by the same code path, so their own consistency check could not reveal it. The export now walks the uncapped `iterateFiles()`, which exists for exactly this: the cap is a per-call guard, not a completeness contract.
diff --git a/src/engine/adapters/wwebjs-chat-transport-death.spec.ts b/src/engine/adapters/wwebjs-chat-transport-death.spec.ts
new file mode 100644
index 000000000..995bcbbe8
--- /dev/null
+++ b/src/engine/adapters/wwebjs-chat-transport-death.spec.ts
@@ -0,0 +1,76 @@
+import type { Client } from 'whatsapp-web.js';
+import { WwebjsChats } from './wwebjs-chats';
+import { createLogger } from '../../common/services/logger.service';
+import { type WwebjsEngineHost } from './wwebjs-host';
+import { type WwebjsMessaging } from './wwebjs-messaging';
+import { EngineTransportError } from '../../common/errors/engine-transport.error';
+
+/**
+ * Five boolean chat operations caught EVERY error and resolved `false`, including a dead-page
+ * transport error — while `getChats` in the same file, and getGroupInfo / getGroupJoinInfo /
+ * getChatsByLabel / getContactById elsewhere in the adapter, split that case out into
+ * EngineTransportError and report the session death.
+ *
+ * The caller was therefore told HTTP 200 `{"success": false}` — "WhatsApp declined a valid request"
+ * — while the session's browser was actually dead, and retried against a corpse instead of getting
+ * the 503 the route documents. The early death signal was lost too, so handlePuppeteerDeath never
+ * fired and the session kept reporting READY until the slower watchdog noticed.
+ */
+const logger = createLogger('wwebjs-chat-transport-death.spec');
+
+describe('boolean chat operations distinguish a dead page from a refusal', () => {
+ const transportError = new Error('Protocol error (Runtime.callFunctionOn): Session closed.');
+
+ function makeChats(reject: unknown): {
+ chats: WwebjsChats;
+ reportIfPageTransportError: jest.Mock;
+ } {
+ const chat = {
+ sendSeen: jest.fn().mockRejectedValue(reject),
+ clearMessages: jest.fn().mockRejectedValue(reject),
+ markUnread: jest.fn().mockRejectedValue(reject),
+ delete: jest.fn().mockRejectedValue(reject),
+ };
+ const client = {
+ getChatById: jest.fn().mockResolvedValue(chat),
+ archiveChat: jest.fn().mockRejectedValue(reject),
+ unarchiveChat: jest.fn().mockRejectedValue(reject),
+ };
+ const reportIfPageTransportError = jest.fn();
+ const host = {
+ ensureReady: jest.fn(),
+ getClient: () => client as unknown as Client,
+ isPageTransportError: (error: unknown) => error === transportError,
+ reportIfPageTransportError,
+ logger,
+ } as unknown as WwebjsEngineHost;
+ return { chats: new WwebjsChats(host, {} as unknown as WwebjsMessaging), reportIfPageTransportError };
+ }
+
+ const call = (chats: WwebjsChats, op: string): Promise<boolean> =>
+ ({
+ sendSeen: () => chats.sendSeen('[email protected]'),
+ clearChatMessages: () => chats.clearChatMessages('[email protected]'),
+ archiveChat: () => chats.archiveChat('[email protected]', true),
+ markUnread: () => chats.markUnread('[email protected]'),
+ deleteChat: () => chats.deleteChat('[email protected]'),
+ })[op]!();
+
+ const OPS = ['sendSeen', 'clearChatMessages', 'archiveChat', 'markUnread', 'deleteChat'];
+
+ it.each(OPS)('%s reports a dead page as a transport failure, not a refusal', async op => {
+ const { chats, reportIfPageTransportError } = makeChats(transportError);
+
+ await expect(call(chats, op)).rejects.toThrow(EngineTransportError);
+ expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, expect.any(String));
+ });
+
+ // Negative twin: an ordinary page-side refusal must still resolve false, unchanged. Without this
+ // the fix could simply turn every failure into a 503.
+ it.each(OPS)('%s still resolves false when the page merely declines', async op => {
+ const { chats, reportIfPageTransportError } = makeChats(new Error('Evaluation failed: chat not found'));
+
+ await expect(call(chats, op)).resolves.toBe(false);
+ expect(reportIfPageTransportError).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.ts
index d95b7f34a..9e2372e79 100644
--- a/src/engine/adapters/wwebjs-chats.ts
+++ b/src/engine/adapters/wwebjs-chats.ts
@@ -76,6 +76,13 @@ export class WwebjsChats {
const chat = await this.client().getChatById(chatId);
return await chat.sendSeen();
} catch (error) {
+ // A dead page is a 503 and an early death signal, not an opaque `false` under a status that
+ // still says READY — the same split getChats and every sibling read already makes. Reporting
+ // this as "WhatsApp declined" let the caller retry against a corpse.
+ if (this.host.isPageTransportError(error)) {
+ this.host.reportIfPageTransportError(error, 'sendSeen');
+ throw new EngineTransportError('Transport died while marking a chat as read');
+ }
this.host.logger.error(`Error marking chat ${chatId} as read`, String(error));
return false;
}
@@ -90,6 +97,13 @@ export class WwebjsChats {
const chat = await this.client().getChatById(chatId);
return await chat.clearMessages();
} catch (error) {
+ // A dead page is a 503 and an early death signal, not an opaque `false` under a status that
+ // still says READY — the same split getChats and every sibling read already makes. Reporting
+ // this as "WhatsApp declined" let the caller retry against a corpse.
+ if (this.host.isPageTransportError(error)) {
+ this.host.reportIfPageTransportError(error, 'clearChatMessages');
+ throw new EngineTransportError('Transport died while clearing a chat');
+ }
this.host.logger.error(`Error clearing messages in chat ${chatId}`, String(error));
return false;
}
@@ -115,6 +129,13 @@ export class WwebjsChats {
}
return true;
} catch (error) {
+ // A dead page is a 503 and an early death signal, not an opaque `false` under a status that
+ // still says READY — the same split getChats and every sibling read already makes. Reporting
+ // this as "WhatsApp declined" let the caller retry against a corpse.
+ if (this.host.isPageTransportError(error)) {
+ this.host.reportIfPageTransportError(error, 'archiveChat');
+ throw new EngineTransportError('Transport died while archiving a chat');
+ }
this.host.logger.error(`Error ${archive ? 'archiving' : 'unarchiving'} chat ${chatId}`, String(error));
return false;
}
@@ -185,6 +206,13 @@ export class WwebjsChats {
await chat.markUnread();
return true;
} catch (error) {
+ // A dead page is a 503 and an early death signal, not an opaque `false` under a status that
+ // still says READY — the same split getChats and every sibling read already makes. Reporting
+ // this as "WhatsApp declined" let the caller retry against a corpse.
+ if (this.host.isPageTransportError(error)) {
+ this.host.reportIfPageTransportError(error, 'markUnread');
+ throw new EngineTransportError('Transport died while marking a chat as unread');
+ }
this.host.logger.error(`Error marking chat ${chatId} as unread`, String(error));
return false;
}
@@ -201,6 +229,13 @@ export class WwebjsChats {
const chat = await this.client().getChatById(chatId);
return await chat.delete();
} catch (error) {
+ // A dead page is a 503 and an early death signal, not an opaque `false` under a status that
+ // still says READY — the same split getChats and every sibling read already makes. Reporting
+ // this as "WhatsApp declined" let the caller retry against a corpse.
+ if (this.host.isPageTransportError(error)) {
+ this.host.reportIfPageTransportError(error, 'deleteChat');
+ throw new EngineTransportError('Transport died while deleting a chat');
+ }
this.host.logger.error(`Error deleting chat ${chatId}`, String(error));
return false;
}