Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): pull the address book after a first link's history sync

Yudhi Armyndharisda380f8538c6
diff --git a/src/engine/adapters/baileys-history.spec.ts b/src/engine/adapters/baileys-history.spec.ts
index 43af7a014..b68d290a1 100644
--- a/src/engine/adapters/baileys-history.spec.ts
+++ b/src/engine/adapters/baileys-history.spec.ts
@@ -209,7 +209,7 @@ describe('hydrateNames', () => {
it('uses the incremental resync on a first link (accountSyncCounter is still 0)', async () => {
// First connect still has Baileys' own snapshot path in flight; forcing another snapshot would
- // race it. Empty contacts here are the boot window, not a missed reconnect.
+ // race it. The lifecycle pulls the address book once that initial sync has gone quiet instead.
const set = jest.fn().mockResolvedValue(undefined);
const resyncAppState = jest.fn().mockResolvedValue(undefined);
const { history: h } = history(
diff --git a/src/engine/adapters/baileys-history.ts b/src/engine/adapters/baileys-history.ts
index af20120b8..15f5f3bfd 100644
--- a/src/engine/adapters/baileys-history.ts
+++ b/src/engine/adapters/baileys-history.ts
@@ -148,6 +148,11 @@ export class BaileysHistory {
* is then PARTIAL rather than empty, and a count-based gate reads partial as "nothing to do" and
* never repairs it. The snapshot pull is the only source that cannot be absorbed, so it runs on its
* own schedule instead of on a count.
+ *
+ * A first link opens with the counter still at 0, so this method skips the pull there; the
+ * lifecycle pulls once the initial history sync has gone quiet instead (see
+ * BaileysLifecycle.scheduleAddressbookRestore). That pull does not count as this instance's one, so
+ * a first reconnect still repairs whatever a late history chunk absorbed again.
*/
async hydrateNames(): Promise<void> {
try {
@@ -211,11 +216,11 @@ export class BaileysHistory {
* then sets `return_snapshot` because the collection has no version. `isInitialSync: true` keeps
* delete-chat mutations from wiping conversations that history is not about to rebuild.
*/
- private async restoreAddressbookSnapshot(): Promise<void> {
+ async restoreAddressbookSnapshot(): Promise<void> {
const name = BaileysHistory.ADDRESSBOOK_COLLECTION;
await this.sock().authState.keys.set({ 'app-state-sync-version': { [name]: null } });
await this.sock().resyncAppState([name], true);
- this.host.logger.debug('Restored address-book snapshot after reconnect', {
+ this.host.logger.debug('Restored address-book snapshot', {
action: 'baileys_restore_addressbook',
contacts: this.host.contactCount(),
});
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index 7edc26e94..065810a62 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -148,6 +148,8 @@ export interface BaileysLifecycleHost {
captureHistoryMessages: BaileysHistory['captureHistoryMessages'];
/** Backfill names the initial sync skipped (runs on connection 'open'). */
hydrateNames: BaileysHistory['hydrateNames'];
+ /** Pull the saved address book from a snapshot (a first link's pull, once its history sync is quiet). */
+ restoreAddressbookSnapshot: BaileysHistory['restoreAddressbookSnapshot'];
/** The currently-registered onQRCode callback, if any (assigned at initialize()). */
getOnQRCode(): EngineEventCallbacks['onQRCode'];
/** The currently-registered onReady callback, if any (assigned at initialize()). */
@@ -170,6 +172,8 @@ export class BaileysLifecycle {
/** A close this long after the previous close means the connection had been healthy in between —
* the backoff counter restarts from scratch instead of inheriting an old incident's attempts. */
private static readonly RECONNECT_STABILITY_RESET_MS = 5 * 60_000;
+ /** How long a first link's history sync must stay silent before the address-book pull runs. */
+ private static readonly ADDRESSBOOK_QUIET_MS = 20_000;
/** Live Baileys socket, null when disconnected. Public so the adapter's `sock` accessor can alias
* it (an unmodified spec pokes `adapter.sock` through a cast; delegate hosts read it live). */
@@ -185,6 +189,8 @@ export class BaileysLifecycle {
private reconnectTimer?: ReturnType<typeof setTimeout>;
/** The current socket's BAILEYS_WS_CONNECTING_DEADLINE_MS backstop. */
private connectingTimer?: ReturnType<typeof setTimeout>;
+ /** A first link's pending address-book pull (see scheduleAddressbookRestore). */
+ private addressbookTimer?: ReturnType<typeof setTimeout>;
/** Date.now() of the last close that scheduled a reconnect — input to the stability reset. */
private lastConnectionCloseAt = 0;
/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */
@@ -391,16 +397,21 @@ export class BaileysLifecycle {
}, BAILEYS_WS_CONNECTING_DEADLINE_MS);
this.connectingTimer.unref();
- sock.ev.on(
- 'creds.update',
- () =>
- void saveCreds().catch(err => {
- this.host.logger.warn('Baileys creds.update save failed', {
- sessionId: this.host.config.sessionId,
- error: err instanceof Error ? err.message : String(err),
- });
- }),
- );
+ // Baileys raises the counter above 0 once, when a first link's initial sync ends (or times out).
+ // Whole-creds emits carry the field too, so only that transition on a first link arms the pull.
+ let awaitingFirstSync = !((state.creds.accountSyncCounter ?? 0) > 0);
+ sock.ev.on('creds.update', update => {
+ void saveCreds().catch(err => {
+ this.host.logger.warn('Baileys creds.update save failed', {
+ sessionId: this.host.config.sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ });
+ if (awaitingFirstSync && (update.accountSyncCounter ?? 0) > 0) {
+ awaitingFirstSync = false;
+ this.scheduleAddressbookRestore(sock);
+ }
+ });
sock.ev.on('connection.update', update => this.handleConnectionUpdate(update));
sock.ev.on('messages.upsert', event => this.host.handleMessagesUpsert(event));
sock.ev.on('messages.update', updates => this.host.handleMessagesUpdate(updates));
@@ -433,6 +444,10 @@ export class BaileysLifecycle {
sock.ev.on('groups.upsert', groups => this.host.handleGroupsUpsert(groups));
sock.ev.on('group.join-request', event => this.host.handleGroupJoinRequest(event));
sock.ev.on('messaging-history.set', history => {
+ // A chunk still arriving means the pull could be absorbed into the next one: wait again.
+ if (this.addressbookTimer) {
+ this.scheduleAddressbookRestore(sock);
+ }
// History sync copies conversation.displayName into `name`, which is a chat title, not the
// address-book saved name (that arrives via contacts.upsert from app-state contactAction).
// Fold the title into notify so chat-name fallback still works, and leave `name` unset so
@@ -468,6 +483,35 @@ export class BaileysLifecycle {
sock.ev.on('presence.update', update => this.host.handlePresenceUpdate(update));
}
+ /**
+ * Pull the address book once a first link's history sync has gone quiet. During the initial sync
+ * Baileys folds saved names into the history batch, where they are stripped as chat titles (see
+ * BaileysHistory.hydrateNames), and that run opens with accountSyncCounter 0, so the pull on
+ * 'open' skips it. Pulling straight away would share the event buffer with the next history chunk
+ * and be absorbed the same way, so every chunk pushes the pull back by the quiet window.
+ */
+ private scheduleAddressbookRestore(sock: WASocket): void {
+ this.cancelAddressbookRestore();
+ this.addressbookTimer = setTimeout(() => {
+ this.addressbookTimer = undefined;
+ if (this.sock !== sock) {
+ return;
+ }
+ this.host.restoreAddressbookSnapshot().catch(err => {
+ this.host.logger.warn('Address-book restore after the initial sync failed', {
+ sessionId: this.host.config.sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ });
+ }, BaileysLifecycle.ADDRESSBOOK_QUIET_MS);
+ this.addressbookTimer.unref();
+ }
+
+ private cancelAddressbookRestore(): void {
+ clearTimeout(this.addressbookTimer);
+ this.addressbookTimer = undefined;
+ }
+
private handleConnectionUpdate(update: {
connection?: string;
qr?: string;
@@ -525,6 +569,7 @@ export class BaileysLifecycle {
if (connection === 'close') {
clearTimeout(this.connectingTimer);
+ this.cancelAddressbookRestore();
const statusCode = (lastDisconnect?.error as { output?: { statusCode?: number } } | undefined)?.output
?.statusCode;
@@ -735,6 +780,7 @@ export class BaileysLifecycle {
this.reconnectTimer = undefined;
}
clearTimeout(this.connectingTimer);
+ this.cancelAddressbookRestore();
void this.sock?.end(undefined);
this.sock = null;
// Cached call handles die with the socket — drop them so a later rejectCall() reports
@@ -816,6 +862,7 @@ export class BaileysLifecycle {
this.reconnectTimer = undefined;
}
clearTimeout(this.connectingTimer);
+ this.cancelAddressbookRestore();
try {
void sourceSock.end(undefined);
} catch {
@@ -900,6 +947,7 @@ export class BaileysLifecycle {
this.reconnectTimer = undefined;
}
clearTimeout(this.connectingTimer);
+ this.cancelAddressbookRestore();
void this.sock?.end(undefined);
this.sock = null;
this.host.liveCalls.clear();
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index b8231f1ff..1f06325d9 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -5172,6 +5172,98 @@ describe('BaileysAdapter contact + chat reads', () => {
});
});
+ describe('address book on a first link', () => {
+ // During a first link's initial sync Baileys folds the app-state contacts.upsert (the saved name)
+ // into the messaging-history.set record it already holds for that id, so the saved name arrives
+ // as a chat title and is stripped. That run opens at accountSyncCounter 0, where hydrateNames
+ // skips the snapshot pull, so the pull has to follow the end of the initial sync instead.
+ const addressbookPulls = (): unknown[] =>
+ fakeSock.authState.keys.set.mock.calls.filter(
+ ([arg]) => JSON.stringify(arg) === JSON.stringify({ 'app-state-sync-version': { critical_unblock_low: null } }),
+ );
+ const absorbed = { id: '[email protected]', name: 'Saved' };
+
+ beforeEach(() => {
+ jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] });
+ fakeSock.authState.creds.accountSyncCounter = 0;
+ });
+ afterEach(() => {
+ jest.useRealTimers();
+ fakeSock.authState.creds.accountSyncCounter = 0;
+ });
+
+ it('pulls the snapshot once the initial history sync goes quiet, and a reconnect still repairs', async () => {
+ const adapter = await ready();
+ await jest.advanceTimersByTimeAsync(0);
+ fakeSock.fire('messaging-history.set', { contacts: [absorbed], chats: [], messages: [] });
+ await expect(adapter.getContacts()).resolves.toHaveLength(0);
+
+ fakeSock.fire('creds.update', { accountSyncCounter: 1 });
+ await jest.advanceTimersByTimeAsync(10_000);
+ // A later chunk pushes the pull back: pulling now would be absorbed into it the same way.
+ fakeSock.fire('messaging-history.set', { contacts: [absorbed], chats: [], messages: [] });
+ await jest.advanceTimersByTimeAsync(15_000);
+ expect(addressbookPulls()).toHaveLength(0);
+
+ await jest.advanceTimersByTimeAsync(5_000);
+ expect(addressbookPulls()).toHaveLength(1);
+ expect(fakeSock.resyncAppState).toHaveBeenCalledWith(['critical_unblock_low'], true);
+ fakeSock.fire('contacts.upsert', [absorbed]);
+ await expect(adapter.getContacts()).resolves.toEqual([
+ expect.objectContaining({ id: '[email protected]', name: 'Saved' }),
+ ]);
+
+ // The first-link pull is not this instance's one reconnect pull, which covers a chunk that
+ // arrived after the quiet window and absorbed the names again.
+ fakeSock.authState.creds.accountSyncCounter = 1;
+ fakeSock.fire('connection.update', { connection: 'open' });
+ await jest.advanceTimersByTimeAsync(0);
+ expect(addressbookPulls()).toHaveLength(2);
+ });
+
+ it('arms the pull only on the counter leaving 0, not on a whole-creds update', async () => {
+ await ready();
+ await jest.advanceTimersByTimeAsync(0);
+ // Baileys emits the whole creds object (counter included) on 'open' and elsewhere.
+ fakeSock.fire('creds.update', { accountSyncCounter: 0, lastPropHash: 'h' });
+ await jest.advanceTimersByTimeAsync(30_000);
+ expect(addressbookPulls()).toHaveLength(0);
+
+ fakeSock.fire('creds.update', { accountSyncCounter: 1 });
+ await jest.advanceTimersByTimeAsync(20_000);
+ expect(addressbookPulls()).toHaveLength(1);
+ fakeSock.fire('creds.update', { accountSyncCounter: 1, lastPropHash: 'h' });
+ await jest.advanceTimersByTimeAsync(30_000);
+ expect(addressbookPulls()).toHaveLength(1);
+ });
+
+ it('never arms the pull on an established session', async () => {
+ const { useMultiFileAuthState } = jest.requireMock<{ useMultiFileAuthState: jest.Mock }>(
+ '@whiskeysockets/baileys',
+ );
+ useMultiFileAuthState.mockResolvedValueOnce({ state: { creds: { accountSyncCounter: 5 }, keys: {} }, saveCreds });
+ fakeSock.authState.creds.accountSyncCounter = 5;
+ await ready();
+ await jest.advanceTimersByTimeAsync(0);
+ const afterOpen = addressbookPulls().length;
+ fakeSock.fire('creds.update', { accountSyncCounter: 5, lastPropHash: 'h' });
+ await jest.advanceTimersByTimeAsync(30_000);
+ expect(addressbookPulls()).toHaveLength(afterOpen);
+ });
+
+ it('drops a pending pull when the connection closes', async () => {
+ await ready();
+ await jest.advanceTimersByTimeAsync(0);
+ fakeSock.fire('creds.update', { accountSyncCounter: 1 });
+ fakeSock.fire('connection.update', {
+ connection: 'close',
+ lastDisconnect: { error: new Boom('lost', { statusCode: 428 }) },
+ });
+ await jest.advanceTimersByTimeAsync(30_000);
+ expect(addressbookPulls()).toHaveLength(0);
+ });
+ });
+
it('contact/chat reads reject with EngineNotReadyError before connect', async () => {
const adapter = newAdapter();
await adapter.initialize({});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 5aa6bf2b4..b5103dfd3 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -187,6 +187,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
handlePresenceUpdate: update => this.events.handlePresenceUpdate(update),
captureHistoryMessages: messages => this.history.captureHistoryMessages(messages),
hydrateNames: () => this.history.hydrateNames(),
+ restoreAddressbookSnapshot: () => this.history.restoreAddressbookSnapshot(),
getOnQRCode: () => this.callbacks.onQRCode,
getOnReady: () => this.callbacks.onReady,
getOnDisconnected: () => this.callbacks.onDisconnected,