Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwebjs): walk a copy of the contact list across yields

Yudhi Armyndharis5d7014c01b05
diff --git a/src/engine/adapters/wwebjs-contacts-read.spec.ts b/src/engine/adapters/wwebjs-contacts-read.spec.ts
index 0da624c76..1499a4e07 100644
--- a/src/engine/adapters/wwebjs-contacts-read.spec.ts
+++ b/src/engine/adapters/wwebjs-contacts-read.spec.ts
@@ -44,6 +44,27 @@ describe('readLeanContacts (in-page contact walk)', () => {
});
});
+ it('walks the contact list as it stood at the start, even if the store grows during a yield', async () => {
+ const models = Array.from({ length: 300 }, (_, i) => String(i));
+ const original = [...models];
+ const read: string[] = [];
+ withModels(models, m => {
+ read.push(m);
+ return row(m);
+ });
+ // A new contact lands at the front of WhatsApp Web's live array while the walk yields.
+ const realSetTimeout = globalThis.setTimeout;
+ jest.spyOn(globalThis, 'setTimeout').mockImplementationOnce((cb: () => void) => {
+ models.unshift('new');
+ return realSetTimeout(cb);
+ });
+
+ const result = await readLeanContacts();
+
+ expect(read).toEqual(original);
+ expect(result.rows.map(r => r.number)).toEqual(original);
+ });
+
it('still yields to the page event loop when the models throw (#1501)', async () => {
withModels(
Array.from({ length: 300 }, (_, i) => String(i)),
diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.ts
index 41b3ff4b3..a149f30d8 100644
--- a/src/engine/adapters/wwebjs-contacts.ts
+++ b/src/engine/adapters/wwebjs-contacts.ts
@@ -56,7 +56,9 @@ export async function readLeanContacts(): Promise<LeanContactRead> {
};
};
};
- const models = w.require('WAWebCollections').Contact.getModelsArray();
+ // A copy: getModelsArray() is the collection's live array, which grows when a new contact writes,
+ // so indexing it across the yields below would read one contact twice and skip another.
+ const models = w.require('WAWebCollections').Contact.getModelsArray().slice();
const rows: LeanContact[] = [];
let failed = 0;
let firstError: string | undefined;