Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(engine): persist Baileys pre-connection history and backfill chat names (#456)

Tobias Strebitzerbd36d82d12b9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 23e1b22d0..0739cb79e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- Sessions (Baileys): pre-connection chat history is now persisted. On a fresh link Baileys pushes the recent (and, with `BAILEYS_SYNC_FULL_HISTORY=true`, full) message history via `messaging-history.set`; these batches are now mapped and saved into the messages table for the chat view, so a newly linked session shows past conversations instead of an empty panel. The batches are de-duplicated and stamped with each message's real timestamp, and are persisted only (no webhook/hook/websocket dispatch, since they predate the live session). Sender push-names from the history are also harvested so chats show names rather than bare ids, and each chat's last-message preview and sort time are seeded from the history so the chat list no longer reads "No messages yet".
+- Sessions (Baileys): chat display names are now backfilled on connect. Baileys 6.7.x frequently skips the initial app-state sync (the state machine goes Online before it runs when the first history notification is non-processable) and the `PUSH_NAME` sync can fail to decrypt, so chats showed bare ids/numbers. On connection open the adapter now fetches group subjects via `groupFetchAllParticipating` and re-triggers an app-state resync (best-effort) to recover saved contact names; both are non-fatal and complement the push-names that arrive on live messages.
+
### Fixed
- Sessions (Baileys): when a session is logged out — unlinked from the phone or via the API — the now-invalid on-disk auth state is cleared, so re-linking shows a fresh QR instead of getting stuck silently reloading the dead credentials. (#453 — thanks @ulises2k)
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 40a888ab5..7e9bd5598 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -1478,6 +1478,8 @@ describe('BaileysAdapter contact + chat reads', () => {
fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
fakeSock.resetEmitter();
jest.clearAllMocks();
+ // Keep hydrateNames() (runs on 'open') inert; clearAllMocks doesn't reset a prior mockResolvedValue.
+ fakeSock.groupFetchAllParticipating.mockResolvedValue({});
});
const ready = async (): Promise<BaileysAdapter> => {
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 6de44fc36..546b67074 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -260,6 +260,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
const h = history as unknown as { lidPnMappings?: { lid: string; pn: string }[]; syncType?: unknown };
const lidPnMappings = h.lidPnMappings;
this.sessionStore.addLidMappings(lidPnMappings ?? []);
+ this.captureHistoryMessages(history.messages ?? []);
this.logger.debug('History sync received', {
action: 'baileys_history_set',
sessionId: this.config.sessionId,
@@ -303,6 +304,8 @@ export class BaileysAdapter implements IWhatsAppEngine {
this.reconnectAttempts = 0;
this.setStatus(EngineStatus.READY);
this.callbacks.onReady?.(this.phoneNumber ?? '', this.pushName ?? '');
+ // Backfill names the initial sync skipped (see hydrateNames).
+ void this.hydrateNames();
}
if (connection === 'close') {
@@ -1111,6 +1114,113 @@ export class BaileysAdapter implements IWhatsAppEngine {
);
}
+ /**
+ * Persist the bulk history Baileys pushes on connect (`messaging-history.set`) - the only
+ * pre-connection history source. Maps each message media-free and hands the batch to the dispatch-free
+ * `onHistoryMessages` callback, harvesting `pushName` into contacts on the way (history `contacts`
+ * carry no names) and seeding each chat's last-message preview.
+ */
+ private captureHistoryMessages(messages: WAMessage[]): void {
+ if (!messages.length) {
+ return;
+ }
+ const nameUpdates: { id: string; notify: string }[] = [];
+ const mapped: IncomingMessage[] = [];
+ for (const msg of messages) {
+ if (msg.key?.fromMe !== true && msg.pushName) {
+ const sender = msg.key?.participant ?? msg.key?.remoteJid;
+ if (sender) {
+ nameUpdates.push({ id: sender, notify: msg.pushName });
+ }
+ }
+ // Seed the chat's last-message preview + sort time (newest wins); else history-only chats
+ // would read "No messages yet".
+ this.sessionStore.recordMessage(msg);
+ const incoming = this.mapHistoryMessage(msg);
+ if (incoming) {
+ mapped.push(incoming);
+ }
+ }
+ if (nameUpdates.length) {
+ this.sessionStore.upsertContacts(nameUpdates);
+ }
+ if (mapped.length) {
+ this.callbacks.onHistoryMessages?.(mapped);
+ }
+ }
+
+ /**
+ * Backfill chat/contact display names after connect. Baileys 6.7.x often skips the initial app-state
+ * sync (the state machine goes Online before it runs) and the PUSH_NAME sync can fail to decrypt, so
+ * names never arrive. Fetch group subjects (reliable) and best-effort re-trigger the app-state sync;
+ * both are non-fatal, and DM push-names still arrive via `contacts.update` on live messages.
+ */
+ private async hydrateNames(): Promise<void> {
+ try {
+ const groups = await this.sock!.groupFetchAllParticipating();
+ const named = Object.values(groups)
+ .filter(g => g?.id && g.subject)
+ .map(g => ({ id: g.id, name: g.subject }));
+ if (named.length) {
+ this.sessionStore.upsertChats(named);
+ this.logger.debug('Hydrated group names', { action: 'baileys_hydrate_groups', count: named.length });
+ }
+ } catch (err) {
+ this.logger.warn('Group name hydration failed', { error: err instanceof Error ? err.message : String(err) });
+ }
+ try {
+ const b = await this.loadLib();
+ await this.sock!.resyncAppState(b.ALL_WA_PATCH_NAMES, false);
+ this.logger.debug('Re-synced app state for contact names', { action: 'baileys_resync_appstate' });
+ } catch (err) {
+ this.logger.warn('App-state resync for contact names failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+
+ /**
+ * Media-free WAMessage -> IncomingMessage map for bulk history (downloading media for thousands of
+ * messages would be ruinous; the type is kept, the payload dropped). Returns null for protocol /
+ * reaction / key / empty messages, which carry nothing for the chat view.
+ */
+ private mapHistoryMessage(msg: WAMessage): IncomingMessage | null {
+ const content = msg.message;
+ if (!content || !msg.key?.remoteJid || !msg.key.id) {
+ return null;
+ }
+ const contentType = Object.keys(content)[0];
+ if (
+ contentType === 'protocolMessage' ||
+ contentType === 'reactionMessage' ||
+ contentType === 'senderKeyDistributionMessage'
+ ) {
+ return null;
+ }
+ const body =
+ content.conversation ??
+ content.extendedTextMessage?.text ??
+ content.imageMessage?.caption ??
+ content.videoMessage?.caption ??
+ content.documentMessage?.caption ??
+ '';
+ return buildIncomingMessageFromBaileys(
+ {
+ id: msg.key.id,
+ remoteJid: msg.key.remoteJid,
+ fromMe: msg.key.fromMe === true,
+ participant: msg.key.participant ?? undefined,
+ body,
+ contentType,
+ isPtt: content.audioMessage?.ptt === true,
+ timestamp: this.toUnixSeconds(msg.messageTimestamp),
+ pushName: msg.pushName ?? undefined,
+ selfJid: this.normalizedSelfJid(),
+ },
+ jid => this.sessionStore.toNeutralJid(jid),
+ );
+ }
+
private normalizedSelfJid(): string {
const phone = this.extractPhone(this.sock?.user?.id);
return phone ? `${phone}@s.whatsapp.net` : '';
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index e87e7fb4a..77983d6e3 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -332,6 +332,11 @@ export interface EngineEventCallbacks {
onMessageAck?: (messageId: string, status: DeliveryStatus) => void;
onMessageRevoked?: (message: RevokedMessage) => void;
onMessageReaction?: (event: ReactionEvent) => void;
+ /**
+ * Bulk historical messages from an engine's initial sync (e.g. Baileys `messaging-history.set`).
+ * They predate the live session, so consumers persist them for the chat view but must not dispatch.
+ */
+ onHistoryMessages?: (messages: IncomingMessage[]) => void;
onDisconnected?: (reason: string) => void;
onStateChanged?: (state: EngineStatus) => void;
/**
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 77875c117..f1adbc6d0 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -432,6 +432,72 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return this.engines.get(id) === engine;
}
+ /**
+ * Persist pre-connection history into the `messages` table for the chat view, without webhook/hook/ws
+ * dispatch (it predates the live session). De-duplicated by `waMessageId` so re-syncs never duplicate.
+ */
+ private async persistHistoryMessages(id: string, messages: IncomingMessage[]): Promise<void> {
+ const byId = new Map<string, IncomingMessage>();
+ for (const m of messages) {
+ // Need an id to de-dup; chatId/from/to are NOT NULL; status/story posts aren't chats.
+ if (m.id && !m.isStatusBroadcast && m.chatId && m.from && m.to) {
+ byId.set(m.id, m);
+ }
+ }
+ if (byId.size === 0) {
+ return;
+ }
+ // Chunk the dedup query: a batch can be thousands, past SQLite's bound-variable limit for IN (...).
+ const ids = [...byId.keys()];
+ const CHUNK = 400;
+ let inserted = 0;
+ for (let i = 0; i < ids.length; i += CHUNK) {
+ const chunkIds = ids.slice(i, i + CHUNK);
+ const existing = await this.messageRepository.find({
+ where: { sessionId: id, waMessageId: In(chunkIds) },
+ select: ['waMessageId'],
+ });
+ const seen = new Set(existing.map(r => r.waMessageId));
+ const rows = chunkIds
+ .filter(x => !seen.has(x))
+ .map(x => {
+ const m = byId.get(x)!;
+ const metadata: Record<string, unknown> = {};
+ if (m.media) metadata.media = m.media;
+ if (m.quotedMessage) metadata.quotedMessage = m.quotedMessage;
+ const row = this.messageRepository.create({
+ sessionId: id,
+ waMessageId: m.id,
+ chatId: m.chatId,
+ from: m.from,
+ to: m.to,
+ body: m.body,
+ type: m.type,
+ direction: m.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING,
+ timestamp: m.timestamp,
+ status: MessageStatus.SENT,
+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
+ });
+ // The chat panel orders by createdAt; stamp the real time so history sorts correctly.
+ if (m.timestamp) {
+ row.createdAt = new Date(m.timestamp * 1000);
+ }
+ return row;
+ });
+ if (rows.length) {
+ await this.messageRepository.save(rows);
+ inserted += rows.length;
+ }
+ }
+ if (inserted) {
+ this.logger.log(`Persisted ${inserted} history message(s)`, {
+ sessionId: id,
+ inserted,
+ action: 'history_messages_persisted',
+ });
+ }
+ }
+
private async initializeEngine(id: string, session: Session): Promise<void> {
this.logger.log(`Initializing engine for session: ${session.name}`, {
sessionId: id,
@@ -588,6 +654,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
})
.catch(err => this.logger.error(`onMessage handler failed for ${id}`, String(err)));
},
+ onHistoryMessages: (messages): void => {
+ if (!this.isLiveEngine(id, engine)) return;
+ // Persist for the chat view only; no dispatch (these predate the live session).
+ void this.persistHistoryMessages(id, messages).catch(err =>
+ this.logger.error(`Failed to persist history messages for ${id}`, String(err)),
+ );
+ },
onMessageCreate: (message): void => {
if (!this.isLiveEngine(id, engine)) return;
// `message_create` fires for every message the account creates, including sends composed on a