Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): answer 503 when mute or pin dies on the write
Yudhi Armyndharis93ebe6b73ef9
diff --git a/src/engine/adapters/wwebjs-chat-transport-death.spec.ts b/src/engine/adapters/wwebjs-chat-transport-death.spec.tsindex 995bcbbe8..2db08c80c 100644--- a/src/engine/adapters/wwebjs-chat-transport-death.spec.ts+++ b/src/engine/adapters/wwebjs-chat-transport-death.spec.ts@@ -74,3 +74,53 @@ describe('boolean chat operations distinguish a dead page from a refusal', () =>expect(reportIfPageTransportError).not.toHaveBeenCalled();});});++/**+ * Mute and pin resolve the chat first and then write. The write leg is where a renderer that dies+ * mid-call rejects, so it needs the same split: a 503 with the death reported, while any other page+ * rejection still reaches the caller unchanged.+ */+describe('mute and pin classify a dead page on the write leg', () => {+ const transportError = new Error('Protocol error (Runtime.callFunctionOn): Target closed');++ function makeChats(reject: unknown): { chats: WwebjsChats; reportIfPageTransportError: jest.Mock } {+ const client = {+ getChatById: jest.fn().mockResolvedValue({ id: { _serialized: '[email protected]' } }),+ muteChat: jest.fn().mockRejectedValue(reject),+ unmuteChat: jest.fn().mockRejectedValue(reject),+ pinChat: jest.fn().mockRejectedValue(reject),+ unpinChat: 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 WRITES: [string, (chats: WwebjsChats) => Promise<unknown>][] = [+ ['muteChat', chats => chats.muteChat('[email protected]', Date.now() + 60_000)],+ ['unmuteChat', chats => chats.muteChat('[email protected]', null)],+ ['pinChat', chats => chats.pinChat('[email protected]', true)],+ ['unpinChat', chats => chats.pinChat('[email protected]', false)],+ ];++ it.each(WRITES)('%s reports a dead page as a transport failure', async (_op, call) => {+ const { chats, reportIfPageTransportError } = makeChats(transportError);++ await expect(call(chats)).rejects.toThrow(EngineTransportError);+ expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, expect.any(String));+ });++ it.each(WRITES)('%s rethrows any other page rejection unchanged', async (_op, call) => {+ const refusal = new Error('Evaluation failed: TypeError: renamed internal');+ const { chats, reportIfPageTransportError } = makeChats(refusal);++ await expect(call(chats)).rejects.toBe(refusal);+ expect(reportIfPageTransportError).not.toHaveBeenCalled();+ });+});diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.tsindex 1096c808e..540a35972 100644--- a/src/engine/adapters/wwebjs-chats.ts+++ b/src/engine/adapters/wwebjs-chats.ts@@ -249,16 +249,36 @@ export class WwebjsChats {if (!chat) throw new BadRequestException(`Chat ${chatId} does not exist on this session`);}+ /**+ * The write leg of mute and pin. A dead page or an expired protocol timeout is the 503 both routes+ * document (mute, unmute, pin and unpin all converge when repeated) and a dead page is reported as+ * the early death signal. Any other rejection is rethrown untouched, for the reason above.+ */+ private async chatWrite<T>(context: string, op: () => Promise<T>): Promise<T> {+ try {+ return await op();+ } catch (error) {+ if (this.host.isPageTransportError(error)) {+ this.host.reportIfPageTransportError(error, context);+ throw new EngineTransportError(`Transport died during ${context}`);+ }+ if (isProtocolTimeout(error)) {+ throw new EngineTransportError(`WhatsApp Web did not answer in time during ${context}`);+ }+ throw error;+ }+ }+async muteChat(chatId: string, muteUntil: number | null): Promise<void> {this.host.ensureReady();await this.requireResolvableChat(chatId);if (muteUntil === null) {- await this.client().unmuteChat(chatId);+ await this.chatWrite('muteChat', () => this.client().unmuteChat(chatId));return;}// muteUntil is epoch milliseconds, which is what Date wants; Client.muteChat floors it to the// seconds its page-side call expects. The Baileys side takes the same milliseconds unmodified.- await this.client().muteChat(chatId, new Date(muteUntil));+ await this.chatWrite('muteChat', () => this.client().muteChat(chatId, new Date(muteUntil)));}async pinChat(chatId: string, pin: boolean): Promise<boolean> {@@ -272,13 +292,13 @@ export class WwebjsChats {// both on its early-out for an already-unpinned chat and after actually unpinning// (Client.js:2073-2084). Forwarding it would report every success as a refusal, the same trap// archiveChat documents. Discard it: an unpin that did not throw succeeded.- await this.client().unpinChat(chatId);+ await this.chatWrite('pinChat', () => this.client().unpinChat(chatId));return true;}// In this direction the return value IS information. WhatsApp caps pinned chats at three// (MAX_PIN_COUNT, Client.js:2054-2063) and the page returns false without pinning once that is// met, so a false here is a real refusal the caller needs to see.- return await this.client().pinChat(chatId);+ return await this.chatWrite('pinChat', () => this.client().pinChat(chatId));}async markUnread(chatId: string): Promise<boolean> {diff --git a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts b/src/engine/adapters/wwebjs-protocol-timeout.spec.tsindex ac9fcae9d..bdece6a25 100644--- a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts+++ b/src/engine/adapters/wwebjs-protocol-timeout.spec.ts@@ -220,6 +220,23 @@ describe('a protocol timeout is a 503, never a not-found verdict', () => {expect(reportIfPageTransportError).not.toHaveBeenCalled();});+ // Mute and pin resolve the chat first, so the write itself is where a slow renderer runs out the budget.+ it.each([+ ['muteChat', (host: WwebjsEngineHost) => chats(host).muteChat(CHAT, Date.now() + 60_000)],+ ['unmuteChat', (host: WwebjsEngineHost) => chats(host).muteChat(CHAT, null)],+ ['pinChat', (host: WwebjsEngineHost) => chats(host).pinChat(CHAT, true)],+ ['unpinChat', (host: WwebjsEngineHost) => chats(host).pinChat(CHAT, false)],+ ] as const)('%s answers a protocolTimeout on its write with a 503 and reports no death', async (method, call) => {+ const timeout = new Error(await puppeteerProtocolTimeoutMessage());+ const { host, reportIfPageTransportError } = makeHost({+ getChatById: jest.fn().mockResolvedValue({ id: { _serialized: CHAT } }),+ [method]: jest.fn().mockRejectedValue(timeout),+ });++ await expect(call(host)).rejects.toBeInstanceOf(EngineTransportError);+ expect(reportIfPageTransportError).not.toHaveBeenCalled();+ });+// The list reads walk the whole store in one command, so they are the ones a large account// pushes past the budget; none has a not-found verdict, but a raw rethrow would answer 500.it.each([