Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): deliver a phone-sent message that arrived while the gateway was down

Yudhi Armyndharis57aa6509ee6d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 784aa0100..8989bf4fe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- Baileys sessions record a message the account sent from its phone while the gateway was down, and dispatch `message.sent` for it, as they already did for one sent while the gateway was online. The offline replay carried the same `append` tag as the library's echo of an API send, which the upsert handler dropped wholesale; it now skips only the ids this session sent itself, and the phone's reactions, edits and revokes from that window are replayed the same way ([#1667](https://github.com/rmyndharis/OpenWA/issues/1667)).
- Baileys sessions no longer drop the inbound messages WhatsApp queued while they were down. The offline replay is tagged `append`, which the upsert handler treated as history and skipped for anything older than the reconnect, so every message sent during an outage was never stored and never dispatched ([#1660](https://github.com/rmyndharis/OpenWA/issues/1660)). Thanks @fransarni for the report.
- A whatsapp-web.js session that comes up without its page-side call hook says so in the log instead of silently never reporting an incoming call. The hook is installed last in the same page evaluate as the message listeners, so the session stays healthy for messages either way ([#1655](https://github.com/rmyndharis/OpenWA/issues/1655)).
- Stopping, unlinking or force-killing a session announces `session.status: disconnected` after the engine is released, not while it is still tearing down, so a dashboard tab or a webhook consumer no longer learns the session is down in the one moment the API still reports its engine as loaded. On whatsapp-web.js that window lasted as long as Chromium took to close, and left an open QR modal on a dead code with the started actions still offered ([#1649](https://github.com/rmyndharis/OpenWA/issues/1649)).
diff --git a/src/engine/adapters/baileys-events.spec.ts b/src/engine/adapters/baileys-events.spec.ts
index 55326f251..b83b21701 100644
--- a/src/engine/adapters/baileys-events.spec.ts
+++ b/src/engine/adapters/baileys-events.spec.ts
@@ -99,6 +99,8 @@ function makeHost(overrides: Partial<BaileysEventsHost> = {}): BaileysEventsHost
recordKeyLidMappings: noop,
recordMessage: noop,
recordMessageEdit: noop,
+ consumeOwnSend: () => false,
+ getStoredMessage: () => undefined,
putStoredMessage: () => undefined,
getOnMessage: () => undefined,
getOnMessageCreate: () => undefined,
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index 0cc09403d..382e83272 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -112,6 +112,13 @@ export interface BaileysEventsHost {
recordMessageEdit(chatId: string, messageId: string, text: string): void;
/** Persist an inbound message to the store; undefined when no store is configured. */
putStoredMessage(msg: WAMessage): Promise<void> | undefined;
+ /**
+ * True exactly once for the id of a message this session sent through the API, whose library echo
+ * is arriving; false for anything the session did not send (see OwnSendRegistry).
+ */
+ consumeOwnSend(id: string | null | undefined): boolean;
+ /** A message this session already delivered or sent, from the persistent store; undefined without a store. */
+ getStoredMessage(messageId: string): Promise<WAMessage | null> | undefined;
/** The currently-registered onMessage callback, if any (assigned at initialize()). */
getOnMessage(): EngineEventCallbacks['onMessage'];
/** The currently-registered onMessageCreate callback, if any (assigned at initialize()). */
@@ -154,18 +161,24 @@ export class BaileysEvents {
if (!msg.message || !msg.key?.remoteJid) {
continue; // protocol/empty messages carry no neutral content
}
- // Baileys echoes back OUR OWN just-sent messages through this same 'append' path, and
- // sendContent() already emits onMessageCreate for those via emitOwnSendEcho() — exclude
- // fromMe on a non-notify batch so that echo doesn't fire onMessageCreate a second time.
- //
- // Everything else on an 'append' batch is live traffic, whatever its timestamp says. The tag
- // marks WhatsApp's offline queue (`node.attrs.offline ? 'append' : 'notify'` in Baileys'
- // messages-recv), i.e. the messages that arrived while this session was down, which by
- // definition predate the reconnect. Real history never reaches this handler: it arrives on
- // messaging-history.set and is captured dispatch-free. Re-delivery is harmless because the
- // insert oracle dedupes on the WhatsApp message id, so a message already stored is not
- // dispatched twice.
- if (event.type !== 'notify' && msg.key.fromMe === true) {
+ // Baileys echoes every message this session sends through the API back through this same
+ // path, tagged 'append', and sendContent() already emits onMessageCreate for those via
+ // emitOwnSendEcho(). WhatsApp replays what the account typed on its phone while the gateway
+ // was down through the same tag (`node.attrs.offline ? 'append' : 'notify'` in Baileys'
+ // messages-recv), and those the session has never seen. Nothing on the batch tells the two
+ // apart except the id, which the adapter recorded when it sent: skip only what we sent, so
+ // the echo cannot fire onMessageCreate twice and the phone's outage-window sends still land
+ // as outgoing messages. Real history never reaches this handler; it arrives on
+ // messaging-history.set and is captured dispatch-free. A re-delivered inbound message is
+ // harmless, since the insert oracle dedupes on the WhatsApp message id and does not dispatch
+ // a stored message again. That oracle does NOT gate dispatch on the own-send path, which is
+ // why the echo has to be caught here, and why a fromMe message the store already holds is
+ // dropped in processInboundMessage before it can be reported a second time.
+ if (msg.key.fromMe === true && this.host.consumeOwnSend(msg.key.id)) {
+ this.host.logger.debug('Skipping the echo of a message this session sent', {
+ msgId: msg.key.id ?? 'unknown',
+ type: event.type,
+ });
continue;
}
// Throttle through the limiter so a burst of media messages can't run unbounded parallel
@@ -337,6 +350,17 @@ export class BaileysEvents {
}
// --- Normal message: enrich + emit ---
+ // A fromMe message the store already holds was delivered or sent before: WhatsApp re-delivers
+ // a node whose ack was lost on a drop, and the own-send path downstream dispatches message.sent
+ // whatever its insert did, so the second copy has to stop here. The store is written by both
+ // the inbound path below and the send path, and it survives a restart, which the registry
+ // consulted in handleMessagesUpsert does not.
+ if (msg.key.fromMe === true && msg.key.id && (await this.host.getStoredMessage(msg.key.id))) {
+ this.host.logger.debug('Skipping a re-delivered message this session already recorded', {
+ msgId: msg.key.id,
+ });
+ return;
+ }
const incoming = await this.mapMessage(msg, contentType, { skipMediaDownload: opts?.skipMedia });
if (msg.key.fromMe === true) {
this.host.getOnMessageCreate()?.(incoming);
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index f352f2357..4c50a34f7 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -48,6 +48,8 @@ export interface BaileysMessagingHost {
loadLib(): Promise<typeof BaileysLib>;
/** Persist a just-sent message to the store; undefined when no store is configured. */
putStoredMessage(msg: WAMessage): Promise<void> | undefined;
+ /** Record the id of a message this session just sent, so its library echo is recognised as ours. */
+ rememberOwnSend(id: string | null | undefined): void;
/** Look up a previously-seen message from the store (the reply/forward/react/delete handle). */
getStoredMessage(messageId: string): Promise<WAMessage | null> | undefined;
/** Remember a lid<->phone pair the socket resolved, so later reads do not have to ask again. */
@@ -220,7 +222,7 @@ export class BaileysMessaging {
}
: {}),
};
- const sent = await this.sock().sendMessage(jid, content, options);
+ const sent = await this.send(jid, content, options);
if (sent) {
void this.host.putStoredMessage(sent)?.catch(err =>
this.host.logger.warn('Failed to persist sent message to store', {
@@ -490,7 +492,7 @@ export class BaileysMessaging {
const target = await this.requireStored(messageId);
this.assertStoredInChat(target, chatId, messageId);
// Resolved like any other send: a lid-migrated contact rejects PN-addressed sends (ack 463).
- await this.sock().sendMessage(await this.toDeliverableJid(chatId), { react: { text: emoji, key: target.key } });
+ await this.send(await this.toDeliverableJid(chatId), { react: { text: emoji, key: target.key } });
}
async deleteMessage(chatId: string, messageId: string, forEveryone = true): Promise<void> {
@@ -498,7 +500,7 @@ export class BaileysMessaging {
const target = await this.requireStored(messageId);
this.assertStoredInChat(target, chatId, messageId);
if (forEveryone) {
- await this.sock().sendMessage(await this.toDeliverableJid(chatId), { delete: target.key });
+ await this.send(await this.toDeliverableJid(chatId), { delete: target.key });
return;
}
// Delete-for-me (revoke on this device only): Baileys exposes it as a chat modification, not a
@@ -540,11 +542,7 @@ export class BaileysMessaging {
// protocolMessage edit envelope, so an edit can re-tag participants. An edit REPLACES the
// content, so omitting mentions drops whatever tags the original carried.
const editContent = { text: body, ...this.withMentions(mentions), edit: target.key };
- const sent = await this.sock().sendMessage(
- jid,
- this.previewSafe(editContent),
- this.previewSafeOptions(editContent),
- );
+ const sent = await this.send(jid, this.previewSafe(editContent), this.previewSafeOptions(editContent));
return { id: sent?.key?.id ?? messageId, timestamp: this.host.toUnixSeconds(sent?.messageTimestamp) };
}
@@ -641,7 +639,7 @@ export class BaileysMessaging {
const jid = await this.toDeliverableJid(chatId);
const safe = this.previewSafe(content);
const merged = this.previewSafeOptions(safe, this.withEphemeral(jid, options));
- const sent = merged ? await this.sock().sendMessage(jid, safe, merged) : await this.sock().sendMessage(jid, safe);
+ const sent = await this.send(jid, safe, merged);
if (sent) {
void this.host.putStoredMessage(sent)?.catch(err =>
this.host.logger.warn('Failed to persist sent message to store', {
@@ -649,8 +647,9 @@ export class BaileysMessaging {
}),
);
// wwjs fires `message_create` for its own API sends, which SessionService turns into `message.sent`.
- // Baileys' own socket-sends echo back only as a `type:'append'` upsert (skipped as history sync), so
- // that event never fired for API sends. Emit the outbound "created" callback here for parity —
+ // Baileys' own socket-sends echo back only as a `type:'append'` upsert, which handleMessagesUpsert
+ // skips by the id send() recorded, so that event never fired for API sends. Emit the outbound
+ // "created" callback here for parity —
// best-effort and off the response path. No media re-download: the API caller already holds the
// payload and the REST send path persists it (wwjs, by contrast, does download it on its echo).
void this.emitOwnSendEcho(sent);
@@ -658,6 +657,25 @@ export class BaileysMessaging {
return { id: sent?.key?.id ?? '', timestamp: this.host.toUnixSeconds(sent?.messageTimestamp) };
}
+ /**
+ * Every message this delegate sends goes through here so its id is recorded before the library
+ * echoes it back. Baileys re-emits each own send through `messages.upsert` tagged `append`, the
+ * same tag WhatsApp uses to replay what the account typed on its phone while the gateway was
+ * down, and the id is the only thing that tells the two apart (see handleMessagesUpsert). The
+ * record is synchronous on the send's own continuation, ahead of the library's buffered echo.
+ */
+ private async send(
+ jid: string,
+ content: Parameters<WASocket['sendMessage']>[1],
+ options?: Parameters<WASocket['sendMessage']>[2],
+ ): Promise<WAMessage | undefined> {
+ const sent = options
+ ? await this.sock().sendMessage(jid, content, options)
+ : await this.sock().sendMessage(jid, content);
+ this.host.rememberOwnSend(sent?.key?.id);
+ return sent;
+ }
+
/**
* Emit the engine-neutral "message created" callback for a message this session just sent via the API,
* so downstream `message.sent` webhook/WS/hook delivery matches the whatsapp-web.js engine. Best-effort:
@@ -745,7 +763,7 @@ export class BaileysMessaging {
// pure ESM and every other site in this codebase defers it to first connect; a module-scope
// require would drag ~590 modules into boot even for whatsapp-web.js-only processes.
const { proto } = await this.host.loadLib();
- await this.sock().sendMessage(await this.toDeliverableJid(chatId), {
+ await this.send(await this.toDeliverableJid(chatId), {
pin: target.key,
type: proto.PinInChat.Type.PIN_FOR_ALL,
// WhatsApp recognises only these three windows; the DTO rejects anything else before we
@@ -760,7 +778,7 @@ export class BaileysMessaging {
this.assertStoredInChat(target, chatId, messageId);
const { proto } = await this.host.loadLib();
// `time` is meaningless for an unpin and is omitted rather than sent as a dummy value.
- await this.sock().sendMessage(await this.toDeliverableJid(chatId), {
+ await this.send(await this.toDeliverableJid(chatId), {
pin: target.key,
type: proto.PinInChat.Type.UNPIN_FOR_ALL,
});
diff --git a/src/engine/adapters/baileys-own-sends.spec.ts b/src/engine/adapters/baileys-own-sends.spec.ts
new file mode 100644
index 000000000..74257d631
--- /dev/null
+++ b/src/engine/adapters/baileys-own-sends.spec.ts
@@ -0,0 +1,44 @@
+import { OwnSendRegistry } from './baileys-own-sends';
+
+/**
+ * The adapter is the only party that knows which `fromMe` messages it sent itself. Baileys echoes
+ * every API send back through `messages.upsert` tagged `append`, and WhatsApp replays messages the
+ * account typed on its phone during an outage through the same tag, so the id is the only thing
+ * that tells the two apart.
+ */
+describe('OwnSendRegistry', () => {
+ it('consumes a remembered id exactly once', () => {
+ const registry = new OwnSendRegistry();
+ registry.remember('A');
+ expect(registry.consume('A')).toBe(true);
+ expect(registry.consume('A')).toBe(false);
+ });
+
+ it('does not claim an id it never sent', () => {
+ const registry = new OwnSendRegistry();
+ expect(registry.consume('PHONE')).toBe(false);
+ expect(registry.consume(undefined)).toBe(false);
+ expect(registry.consume(null)).toBe(false);
+ });
+
+ it('ignores an empty id rather than remembering it', () => {
+ const registry = new OwnSendRegistry();
+ registry.remember(undefined);
+ registry.remember(null);
+ registry.remember('');
+ expect(registry.size).toBe(0);
+ });
+
+ // An echo that never arrives (the library option off, a send whose id could not be read back)
+ // would otherwise leave its id behind forever on a gateway that runs for months.
+ it('forgets the oldest ids once the cap is reached', () => {
+ const registry = new OwnSendRegistry(3);
+ registry.remember('A');
+ registry.remember('B');
+ registry.remember('C');
+ registry.remember('D');
+ expect(registry.size).toBe(3);
+ expect(registry.consume('A')).toBe(false);
+ expect(registry.consume('D')).toBe(true);
+ });
+});
diff --git a/src/engine/adapters/baileys-own-sends.ts b/src/engine/adapters/baileys-own-sends.ts
new file mode 100644
index 000000000..1ed57cf5c
--- /dev/null
+++ b/src/engine/adapters/baileys-own-sends.ts
@@ -0,0 +1,43 @@
+/**
+ * The ids of the messages this session sent through the API, held until the library's own echo of
+ * each comes back through `messages.upsert`.
+ *
+ * Baileys re-emits every own send tagged `append`, and WhatsApp replays what the account typed on
+ * its phone while the gateway was down through the same tag with the same `fromMe`. The id is the
+ * only thing that tells the two apart, and the adapter is the only party that knows it, because it
+ * made the send. An echo is consumed once and forgotten; anything not recorded here was not sent by
+ * this process and is delivered.
+ *
+ * Bounded, oldest first: an echo that never arrives (the library option off, a send whose id could
+ * not be read back) must not leave its id behind forever on a gateway that runs for months. The
+ * library echo is local and arrives within the event buffer's window, so this only has to outlast
+ * that; an id evicted early, and any message WhatsApp itself re-delivers, is caught instead by the
+ * persistent message store check in processInboundMessage, which does survive a restart.
+ */
+export class OwnSendRegistry {
+ private readonly ids = new Set<string>();
+
+ constructor(private readonly cap = 1000) {}
+
+ get size(): number {
+ return this.ids.size;
+ }
+
+ remember(id: string | null | undefined): void {
+ if (!id) return;
+ // Re-inserting moves the id to the newest position, so a resend is not evicted early.
+ this.ids.delete(id);
+ this.ids.add(id);
+ while (this.ids.size > this.cap) {
+ const oldest = this.ids.values().next().value;
+ if (oldest === undefined) break;
+ this.ids.delete(oldest);
+ }
+ }
+
+ /** True exactly once for an id this session sent; false for anything else, including no id. */
+ consume(id: string | null | undefined): boolean {
+ if (!id) return false;
+ return this.ids.delete(id);
+ }
+}
diff --git a/src/engine/adapters/baileys-quoted-send.spec.ts b/src/engine/adapters/baileys-quoted-send.spec.ts
index 2695383d6..1c6597ccf 100644
--- a/src/engine/adapters/baileys-quoted-send.spec.ts
+++ b/src/engine/adapters/baileys-quoted-send.spec.ts
@@ -48,6 +48,7 @@ function makeMessaging(stored: unknown = STORED): {
loadLib: () => Promise.resolve({} as never),
getStoredMessage,
putStoredMessage: () => undefined,
+ rememberOwnSend: () => undefined,
recordLidMapping: () => undefined,
getOnMessageCreate: () => undefined,
mapMessage: () => Promise.resolve({} as never),
diff --git a/src/engine/adapters/baileys-status.ts b/src/engine/adapters/baileys-status.ts
index ecaf64df6..a9f57986c 100644
--- a/src/engine/adapters/baileys-status.ts
+++ b/src/engine/adapters/baileys-status.ts
@@ -18,6 +18,8 @@ export interface BaileysStatusHost {
normalizedSelfJid(): string;
/** Baileys timestamps are `number | Long`; normalize to unix seconds. */
toUnixSeconds(ts: number | { toNumber(): number } | null | undefined): number;
+ /** Record the id of a message this session just sent, so its library echo is recognised as ours. */
+ rememberOwnSend(id: string | null | undefined): void;
}
export class BaileysStatus {
@@ -72,7 +74,7 @@ export class BaileysStatus {
*/
async deleteStatus(statusId: string): Promise<void> {
this.host.ensureReady();
- await this.sock().sendMessage('status@broadcast', {
+ const sent = await this.sock().sendMessage('status@broadcast', {
delete: {
remoteJid: 'status@broadcast',
fromMe: true,
@@ -80,13 +82,14 @@ export class BaileysStatus {
participant: this.host.toEngineJid(this.host.normalizedSelfJid()),
},
});
+ this.host.rememberOwnSend(sent?.key?.id);
}
/**
* Post a status (story) to `status@broadcast` with a denormalized `statusJidList` (the allow-list of
* neutral recipients folded back to the engine dialect). Image/video variants route through here too.
- * The outbound status echo is NOT persisted — status isn't a chat message (the inbound filter in
- * handleMessagesUpsert already skips `type:'append'` echoes).
+ * The outbound status echo is NOT persisted — status isn't a chat message (its id is recorded below
+ * so handleMessagesUpsert skips the `type:'append'` echo as ours).
*/
private async postStatus(content: AnyMessageContent, options: StatusPostOptions): Promise<StatusResult> {
this.host.ensureReady();
@@ -102,6 +105,7 @@ export class BaileysStatus {
backgroundColor: options.backgroundColor,
font: options.font,
});
+ this.host.rememberOwnSend(sent?.key?.id);
return this.toStatusResult(sent);
}
diff --git a/src/engine/adapters/baileys-sticker-webp.spec.ts b/src/engine/adapters/baileys-sticker-webp.spec.ts
index c77cb4166..fad9a72dc 100644
--- a/src/engine/adapters/baileys-sticker-webp.spec.ts
+++ b/src/engine/adapters/baileys-sticker-webp.spec.ts
@@ -59,6 +59,7 @@ function makeMessaging(): { messaging: BaileysMessaging; sock: { sendMessage: je
loadLib: () => Promise.resolve({} as never),
getStoredMessage: () => Promise.resolve(undefined),
putStoredMessage: () => undefined,
+ rememberOwnSend: () => undefined,
recordLidMapping: () => undefined,
getOnMessageCreate: () => undefined,
mapMessage: () => Promise.resolve({} as never),
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 5987a0f56..4acf6a3b1 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -168,6 +168,12 @@ const fakeStore = {
clearSession: jest.fn().mockResolvedValue(undefined),
};
+// clearAllMocks keeps implementations: a store lookup one test taught to return a message must not
+// make a later fromMe delivery look like a re-delivered one (processInboundMessage drops those).
+beforeEach(() => {
+ fakeStore.getMessage.mockReset();
+});
+
/** A fresh async-iterable stream of the given chunks (the shape `downloadMediaMessage('stream')` returns). */
function streamOf(...chunks: Buffer[]): AsyncIterable<Buffer> & { destroy: () => void } {
return {
@@ -2324,29 +2330,87 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(onMessage).toHaveBeenCalled();
});
- it('does not double-fire onMessageCreate for a recent append echo of our own send', async () => {
- // Baileys echoes our own just-sent messages back through messages.upsert tagged 'append' too.
- // sendContent() already emits onMessageCreate for those via emitOwnSendEcho() (not exercised by
- // this fakeSock harness) — the recency override must stay scoped to fromMe !== true so this
- // path doesn't ALSO fire onMessageCreate a second time for the same send.
+ // Baileys echoes every API send back through messages.upsert tagged 'append', and sendContent()
+ // already emits onMessageCreate for it via emitOwnSendEcho(). The echo is told apart by its id,
+ // which the adapter recorded when it sent; nothing else on the batch distinguishes it from a
+ // message the phone typed while the gateway was down.
+ it('does not double-fire onMessageCreate for the append echo of a message this session sent', async () => {
+ fakeSock.sendMessage.mockResolvedValue({
+ key: { remoteJid: '[email protected]', fromMe: true, id: 'OWN_ECHO' },
+ message: { conversation: 'sent by us' },
+ messageTimestamp: 1700000001,
+ });
const onMessage = jest.fn();
const onMessageCreate = jest.fn();
const adapter = newAdapter();
await adapter.initialize({ onMessage, onMessageCreate });
- fakeSock.fire('connection.update', { connection: 'open' }); // sets connectedAt
+ fakeSock.fire('connection.update', { connection: 'open' });
+ await adapter.sendTextMessage('[email protected]', 'sent by us');
+ await new Promise(r => setImmediate(r));
+ expect(onMessageCreate).toHaveBeenCalledTimes(1); // the adapter's own echo
+
fakeSock.fire('messages.upsert', {
type: 'append',
messages: [
{
key: { remoteJid: '[email protected]', fromMe: true, id: 'OWN_ECHO' },
message: { conversation: 'sent by us' },
- messageTimestamp: Math.floor(Date.now() / 1000),
+ messageTimestamp: 1700000001,
},
],
});
await new Promise(r => setImmediate(r));
expect(onMessage).not.toHaveBeenCalled();
- expect(onMessageCreate).not.toHaveBeenCalled();
+ expect(onMessageCreate).toHaveBeenCalledTimes(1); // the library echo added nothing
+ });
+
+ // The account's own phone kept working while the gateway was down. WhatsApp replays what it sent
+ // in that window through the same 'append' tag as the API echo above, and only the id says it is
+ // not ours. It is an outgoing message the session never saw, so it goes out as onMessageCreate.
+ it('delivers a message the phone sent while the gateway was down', async () => {
+ const onMessage = jest.fn();
+ const onMessageCreate = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessage, onMessageCreate });
+ fakeSock.fire('connection.update', { connection: 'open' });
+ fakeSock.fire('messages.upsert', {
+ type: 'append',
+ messages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: true, id: 'TYPED_ON_PHONE' },
+ message: { conversation: 'replied from the phone during the outage' },
+ messageTimestamp: Math.floor(Date.now() / 1000) - 3600,
+ },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ expect(onMessage).not.toHaveBeenCalled();
+ expect(onMessageCreate).toHaveBeenCalledTimes(1);
+ });
+
+ // WhatsApp re-delivers a node whose ack was lost on a socket drop. The inbound path is deduped by
+ // the session's insert oracle, but the own-send path dispatches message.sent whatever the insert
+ // did, so a phone-sent message delivered twice has to be caught before it leaves the adapter. The
+ // store already holds everything this session delivered or sent, and it survives a restart.
+ it('does not dispatch a phone-sent message twice when WhatsApp re-delivers it', async () => {
+ const replayed = {
+ key: { remoteJid: '[email protected]', fromMe: true, id: 'TYPED_ON_PHONE' },
+ message: { conversation: 'replied from the phone during the outage' },
+ messageTimestamp: Math.floor(Date.now() / 1000) - 3600,
+ };
+ fakeStore.getMessage.mockResolvedValueOnce(null).mockResolvedValueOnce(replayed);
+ const onMessageCreate = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessageCreate });
+ fakeSock.fire('connection.update', { connection: 'open' });
+
+ fakeSock.fire('messages.upsert', { type: 'append', messages: [replayed] });
+ await new Promise(r => setImmediate(r));
+ expect(onMessageCreate).toHaveBeenCalledTimes(1);
+
+ fakeSock.fire('messages.upsert', { type: 'append', messages: [replayed] }); // the unacked re-delivery
+ await new Promise(r => setImmediate(r));
+ expect(onMessageCreate).toHaveBeenCalledTimes(1);
});
it('emits onMessageAck from messages.update with a neutral status', async () => {
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 790997c71..e28e0a6a2 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -9,6 +9,7 @@ import { BaileysEvents } from './baileys-events';
import { BaileysGroups } from './baileys-groups';
import { BaileysHistory, toUnixSeconds } from './baileys-history';
import { type BaileysEngineHost } from './baileys-host';
+import { OwnSendRegistry } from './baileys-own-sends';
import { BaileysLifecycle } from './baileys-lifecycle';
import { BaileysMessaging } from './baileys-messaging';
import { BaileysStatus } from './baileys-status';
@@ -105,6 +106,9 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.lifecycle.loadLib();
}
+ /** Ids of the messages this session sent through the API, until each one's library echo returns. */
+ private readonly ownSends = new OwnSendRegistry();
+
constructor(private readonly config: BaileysAdapterConfig) {
// Isolate each session's auth state under its own subdirectory of the shared auth dir.
this.authPath = baileysAuthDir(config.authDir, config.sessionId);
@@ -130,6 +134,8 @@ export class BaileysAdapter implements IWhatsAppEngine {
recordMessage: msg => this.sessionStore.recordMessage(msg),
recordMessageEdit: (chatId, messageId, text) => this.sessionStore.recordMessageEdit(chatId, messageId, text),
putStoredMessage: msg => this.config.messageStore?.put(this.config.dbSessionId, msg),
+ rememberOwnSend: id => this.ownSends.remember(id),
+ consumeOwnSend: id => this.ownSends.consume(id),
getOnMessage: () => this.callbacks.onMessage,
getOnMessageCreate: () => this.callbacks.onMessageCreate,
getOnMessageRevoked: () => this.callbacks.onMessageRevoked,
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 2a6e019c1..06b5478b9 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -5261,8 +5261,8 @@ describe('SessionService', () => {
it('does not process an own-send status echo (type=append) — no dispatch, no WS emit, no DB write', async () => {
// Regression guard for the WhatsApp Status feature: posting a status produces an own-send echo
// that Baileys delivers as `messages.upsert` with `type: 'append'` (NOT 'notify'). The adapter's
- // handleMessagesUpsert filters `type !== 'notify'` before processInboundMessage, so the echo never
- // reaches the engine callbacks. This test pins the engine-neutral last-chance guard —
+ // handleMessagesUpsert recognises the echo by the id the status post recorded and skips it before
+ // processInboundMessage, so it never reaches the engine callbacks. This test pins the engine-neutral last-chance guard —
// `isStatusBroadcast` on both onMessageCreate and onMessage — so a future change can't silently
// leak a status echo to websockets, webhooks, or the message table. Asserts the full no-side-effect
// contract (webhook dispatch + WS emit + DB insert) for completeness, even though the existing