Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): list contacts when WhatsApp Web cannot read one
Yudhi Armyndharis5f446bac854e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9c1f47289..ff4324cb8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- A plugin `configUi` editor receives the dashboard language as `locale` in `config:value`, and the `schema` it gets carries field titles and descriptions localized from the manifest `i18n` block, as the generated form already showed. Thanks @probably-ABHINAV, and @TreIngenia for the proposal.+- whatsapp-web.js: `GET /api/sessions/:sessionId/contacts` no longer fails with `500` when WhatsApp Web cannot read one contact (`getAlternateUserWid - Invalid get call using deviceWid`). That contact is skipped and counted in a warning, and the rest of the list is returned ([#1720](https://github.com/rmyndharis/OpenWA/issues/1720)). Thanks @onepay-ye for the report.## [0.23.7] - 2026-09-25diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 6035163a4..e1d30951b 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -6012,7 +6012,7 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-},{ id: { $1: '[email protected]' }, name: 'Bob', pushname: 'Bobby', number: '222', isMyContact: false, isBlocked: true },];- const evaluate = jest.fn().mockResolvedValue(raw);+ const evaluate = jest.fn().mockResolvedValue({ rows: raw, failed: 0 });const { adapter } = readyAdapter({ pupPage: { evaluate } });await expect(adapter.getContacts()).resolves.toEqual([@@ -6029,7 +6029,7 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-const good1 = { id: { _serialized: '[email protected]' }, name: 'Alice', number: '111' };const unreadable = { id: {}, name: 'Ghost', number: '000' };const good2 = { id: { $1: '[email protected]' }, name: 'Bob', number: '222' };- const evaluate = jest.fn().mockResolvedValue([good1, unreadable, good2]);+ const evaluate = jest.fn().mockResolvedValue({ rows: [good1, unreadable, good2], failed: 0 });const { adapter } = readyAdapter({ pupPage: { evaluate } });const logger = (adapter as unknown as { logger: { warn: (m: string) => void } }).logger;const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);@@ -6040,6 +6040,28 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-expect(warnSpy).toHaveBeenCalledWith('Skipped 1 contact(s) without a serialized id');});+ // #1720: a contact model WhatsApp Web cannot read is skipped in-page; the rest of the address+ // book still answers, and the count and first error reach one warn line.+ it('keeps the readable contacts when WhatsApp Web could not read some, and warns once', async () => {+ const good = { id: { _serialized: '[email protected]' }, name: 'Alice', number: '111' };+ const evaluate = jest.fn().mockResolvedValue({+ rows: [good],+ failed: 2,+ firstError: 'getAlternateUserWid - Invalid get call using deviceWid',+ });+ const { adapter, onDisconnected } = readyAdapter({ pupPage: { evaluate } });+ const logger = (adapter as unknown as { logger: { warn: (m: string, c?: unknown) => void } }).logger;+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);++ const contacts = await adapter.getContacts();++ expect(contacts.map(c => c.id)).toEqual(['[email protected]']);+ expect(warnSpy).toHaveBeenCalledWith('Skipped 2 contact(s) WhatsApp Web could not read', {+ error: 'getAlternateUserWid - Invalid get call using deviceWid',+ });+ expect(onDisconnected).not.toHaveBeenCalled();+ });+// A rejection that carries no transport-death signature is an ordinary failure, not a dead page —// it must reach the caller unchanged and leave the session READY, unlike the 503 case above.it('propagates a non-transport rejection from getContacts untouched and leaves the session READY', async () => {diff --git a/src/engine/adapters/wwebjs-contacts-read.spec.ts b/src/engine/adapters/wwebjs-contacts-read.spec.tsnew file mode 100644index 000000000..0da624c76--- /dev/null+++ b/src/engine/adapters/wwebjs-contacts-read.spec.ts@@ -0,0 +1,61 @@+import { readLeanContacts } from './wwebjs-contacts';++/**+ * readLeanContacts runs inside the WhatsApp Web page (page.evaluate), so these drive it against a+ * stand-in `window` rather than through the adapter, where the evaluate is mocked away.+ */+describe('readLeanContacts (in-page contact walk)', () => {+ const g = globalThis as unknown as { window?: unknown };++ afterEach(() => {+ delete g.window;+ jest.restoreAllMocks();+ });++ function withModels(models: string[], getContactModel: (m: string) => unknown): void {+ g.window = {+ require: () => ({ Contact: { getModelsArray: () => models } }),+ WWebJS: { getContactModel },+ };+ }++ const row = (m: string) => ({+ id: `${m}@c.us`,+ name: m,+ pushname: m,+ userid: m,+ isMyContact: true,+ isBlocked: false,+ });++ it('skips a model WhatsApp Web cannot read and keeps the rest (#1720)', async () => {+ withModels(['111', 'device', '222'], m => {+ if (m === 'device') throw new Error('getAlternateUserWid - Invalid get call using deviceWid');+ return row(m);+ });++ await expect(readLeanContacts()).resolves.toEqual({+ rows: [+ { id: '[email protected]', name: '111', pushname: '111', number: '111', isMyContact: true, isBlocked: false },+ { id: '[email protected]', name: '222', pushname: '222', number: '222', isMyContact: true, isBlocked: false },+ ],+ failed: 1,+ firstError: 'getAlternateUserWid - Invalid get call using deviceWid',+ });+ });++ it('still yields to the page event loop when the models throw (#1501)', async () => {+ withModels(+ Array.from({ length: 300 }, (_, i) => String(i)),+ () => {+ throw new Error('unreadable');+ },+ );+ const timers = jest.spyOn(globalThis, 'setTimeout');++ const read = await readLeanContacts();++ expect(read).toEqual({ rows: [], failed: 300, firstError: 'unreadable' });+ expect(timers).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex 85ae40614..b90457a4e 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -19,6 +19,13 @@ interface LeanContact {isBlocked: boolean;}+/** What {@link readLeanContacts} returns: the readable rows, and how many models threw instead. */+interface LeanContactRead {+ rows: LeanContact[];+ failed: number;+ firstError?: string;+}+/*** Read the contact list IN-PAGE, projected to only the fields {@link WwebjsContacts.toContact} keeps,* yielding to the page event loop every 256 contacts so the liveness probe's queued `getState()`@@ -34,7 +41,7 @@ interface LeanContact {* `BusinessProfile.find` is skipped: its only output, `res.businessProfile`, is not one of the six* fields, so dropping it costs nothing and saves a network fetch per business contact.*/-export async function readLeanContacts(): Promise<LeanContact[]> {+export async function readLeanContacts(): Promise<LeanContactRead> {const w = window as unknown as {require: (m: string) => { Contact: { getModelsArray: () => unknown[] } };WWebJS: {@@ -49,22 +56,33 @@ export async function readLeanContacts(): Promise<LeanContact[]> {};};const models = w.require('WAWebCollections').Contact.getModelsArray();- const out: LeanContact[] = [];+ const rows: LeanContact[] = [];+ let failed = 0;+ let firstError: string | undefined;for (let i = 0; i < models.length; i++) {- const m = w.WWebJS.getContactModel(models[i]);- out.push({- id: m.id,- name: m.name,- pushname: m.pushname,- number: m.userid,- isMyContact: m.isMyContact,- isBlocked: m.isBlocked,- });+ // One model WhatsApp Web cannot read (getContactModel's getAlternateUserWid throws "Invalid get+ // call using deviceWid" for a device-scoped wid, #1720) must not reject the whole walk. It is+ // counted and skipped; whatsapp-web.js's own getContacts() never returned such an entry either,+ // because its Promise.all rejected on it.+ try {+ const m = w.WWebJS.getContactModel(models[i]);+ rows.push({+ id: m.id,+ name: m.name,+ pushname: m.pushname,+ number: m.userid,+ isMyContact: m.isMyContact,+ isBlocked: m.isBlocked,+ });+ } catch (error) {+ failed++;+ if (firstError === undefined) firstError = error instanceof Error ? error.message : String(error);+ }// Yield every 256 contacts so the getState() liveness probe can interleave (#1501);// raise the stride if the read ever gets too chatty on a very large address book.if ((i & 0xff) === 0xff) await new Promise(resolve => setTimeout(resolve));}- return out;+ return { rows, failed, firstError };}/**@@ -103,13 +121,18 @@ export class WwebjsContacts {this.host.ensureReady();let raw: RawWwebjsContact[];+ let unreadable: number;+ let firstError: string | undefined;try {// A direct in-page walk that yields so the liveness probe is not starved (see readLeanContacts,// #1501), instead of whatsapp-web.js's atomic client.getContacts(). The projected rows are a// strict subset of a Contact; the mapping below reads only those six fields.const page = (this.client() as unknown as { pupPage?: { evaluate: <T>(fn: () => Promise<T>) => Promise<T> } }).pupPage;- raw = ((await page?.evaluate(readLeanContacts)) ?? []) as unknown as RawWwebjsContact[];+ const read = await page?.evaluate(readLeanContacts);+ raw = (read?.rows ?? []) as unknown as RawWwebjsContact[];+ unreadable = read?.failed ?? 0;+ firstError = read?.firstError;} catch (error) {// A dead page surfaces here as a raw Puppeteer error; convert it to the documented transport// failure the way wwebjs-chats.ts does, so a transport death answers 503 instead of a bare 500.@@ -136,6 +159,9 @@ export class WwebjsContacts {if (skipped > 0) {this.host.logger.warn(`Skipped ${skipped} contact(s) without a serialized id`);}+ if (unreadable > 0) {+ this.host.logger.warn(`Skipped ${unreadable} contact(s) WhatsApp Web could not read`, { error: firstError });+ }return contacts;}