Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): quote the edited text while a repeat is stored

Yudhi Armyndharis4965e905f831
diff --git a/src/engine/adapters/baileys-click-button.spec.ts b/src/engine/adapters/baileys-click-button.spec.ts
index 32269fd31..f5d32052a 100644
--- a/src/engine/adapters/baileys-click-button.spec.ts
+++ b/src/engine/adapters/baileys-click-button.spec.ts
@@ -85,6 +85,7 @@ function makeMessaging(stored: unknown = PROMPT, opts: { ephemeralExpiration?: n
} as never),
getStoredMessage,
wasDeletedForEveryone: () => false,
+ pendingEditOf: () => undefined,
markDeletedForEveryone: () => undefined,
putStoredMessage,
recordMessage: () => undefined,
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index 28b708e55..0d9759540 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -200,8 +200,9 @@ export class BaileysEvents {
/**
* The latest edit of a message still being processed, by id, with the key it was sent under. The
* edit is announced first and finds no row or preview to change, and a repeat delivery can be stored
- * after the edit was applied, so the original is stored and announced with this text instead.
- * Bounded like deletedForEveryone, which wins over it.
+ * after the edit was applied, so the original is stored and announced with this text instead, and
+ * a quote or forward meanwhile carries it too (see pendingEditOf). Dropped once the message's
+ * processing settles, and bounded like deletedForEveryone, which wins over it.
*/
private readonly editedWhileInFlight = new Map<string, { envelope: WAMessageKey; body: string }>();
@@ -212,6 +213,16 @@ export class BaileysEvents {
return this.deletedForEveryone.has(messageId);
}
+ /**
+ * The text of an edit announced while this message is still being processed, when that edit may
+ * change `target`, the key of the copy about to be quoted or forwarded. The stored copy catches up
+ * once the processing settles, but a repeat delivery can already be stored with the old text.
+ */
+ pendingEditOf(messageId: string, target: WAMessageKey): string | undefined {
+ const edit = this.inboundInFlight.has(messageId) ? this.editedWhileInFlight.get(messageId) : undefined;
+ return edit && this.mayChange(target, edit.envelope, false) ? edit.body : undefined;
+ }
+
/** Record an accepted delete for everyone of this message (see deletedForEveryone). */
markDeletedForEveryone(messageId: string): void {
this.deletedForEveryone.add(messageId);
@@ -288,7 +299,10 @@ export class BaileysEvents {
};
this.inboundInFlight.set(id, tracked);
void tracked.done.finally(() => {
- if (this.inboundInFlight.get(id) === tracked) this.inboundInFlight.delete(id);
+ if (this.inboundInFlight.get(id) !== tracked) return;
+ this.inboundInFlight.delete(id);
+ // The edit's store write was chained behind this, so the store carries it (or a newer one) now.
+ this.editedWhileInFlight.delete(id);
});
}
}
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index 5cd8a77bd..a2c7ef3f3 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -1,5 +1,11 @@
import type * as BaileysLib from '@whiskeysockets/baileys';
-import type { AnyMessageContent, MiscMessageGenerationOptions, WAMessage, WASocket } from '@whiskeysockets/baileys';
+import type {
+ AnyMessageContent,
+ MiscMessageGenerationOptions,
+ WAMessage,
+ WAMessageKey,
+ WASocket,
+} from '@whiskeysockets/baileys';
import { generateSafeLinkPreview } from './safe-link-preview';
import {
CallLinkType,
@@ -64,6 +70,8 @@ export interface BaileysMessagingHost {
wasDeletedForEveryone(messageId: string): boolean;
/** Record a delete for everyone this session just made (see wasDeletedForEveryone). */
markDeletedForEveryone(messageId: string): void;
+ /** The text of an edit of this message the stored copy with key `target` does not show yet, if any. */
+ pendingEditOf(messageId: string, target: WAMessageKey): string | undefined;
/** Remember a lid<->phone pair the socket resolved, so later reads do not have to ask again. */
recordLidMapping(lid: string, pn: string): void;
/** The currently-registered onMessageCreate callback, if any (assigned at initialize()). */
@@ -823,7 +831,8 @@ export class BaileysMessaging {
* `allowDeleted`: quoting it would hand WhatsApp the deleted content again (Baileys copies the
* quoted message into the reply's contextInfo), and there is nothing left to forward, react to or
* edit. A message the session knows was deleted is treated the same while its stored copy still
- * holds the content, as it can when the delete overtook the original's own store write.
+ * holds the content, as it can when the delete overtook the original's own store write. An edit
+ * that overtook it the same way is applied to a copy, so a quote or forward carries the edited text.
*/
private async requireStored(messageId: string, allowDeleted = false): Promise<WAMessage> {
const found = await this.host.getStoredMessage(messageId);
@@ -831,7 +840,13 @@ export class BaileysMessaging {
if (!found?.key || (deleted && !allowDeleted)) {
throw new MessageNotFoundError(messageId);
}
- return found;
+ const edited = deleted ? undefined : this.host.pendingEditOf(messageId, found.key);
+ if (edited === undefined) return found;
+ const b = await this.host.loadLib();
+ const copy = JSON.parse(JSON.stringify(found, b.BufferJSON.replacer), b.BufferJSON.reviver) as WAMessage;
+ const content = b.normalizeMessageContent(copy.message ?? undefined);
+ if (content) setBaileysText(content, edited);
+ return copy;
}
/** Apply a change this session just made to the stored copy. Best-effort: the change already went out. */
diff --git a/src/engine/adapters/baileys-quote-on-receipt.spec.ts b/src/engine/adapters/baileys-quote-on-receipt.spec.ts
index 6725c32df..f6381c5aa 100644
--- a/src/engine/adapters/baileys-quote-on-receipt.spec.ts
+++ b/src/engine/adapters/baileys-quote-on-receipt.spec.ts
@@ -134,6 +134,7 @@ describe('quoting a Baileys message the moment it is announced', () => {
mapMessage: (...a: Parameters<BaileysEvents['mapMessage']>) => events.mapMessage(...a),
wasDeletedForEveryone: (id: string) => events.wasDeletedForEveryone(id),
markDeletedForEveryone: (id: string) => events.markDeletedForEveryone(id),
+ pendingEditOf: (id: string, key: WAMessage['key']) => events.pendingEditOf(id, key),
});
return { events, messaging, sock };
};
@@ -384,6 +385,62 @@ describe('quoting a Baileys message the moment it is announced', () => {
expect(heard).toEqual(['fixed caption', 'fixed caption']);
});
+ it('lets a consumer of the edit quote the edited text while a repeat of the original is stored', async () => {
+ let reply: Promise<unknown> | undefined;
+ const { events, messaging, sock } = build(() => undefined, {
+ edited: () => {
+ reply = messaging.replyToMessage(CHAT, 'TARGET', 'ok');
+ },
+ });
+ events.handleMessagesUpsert({ messages: [photo('TARGET')], type: 'notify' });
+ await ticks();
+ events.handleMessagesUpsert({ messages: [photo('TARGET')], type: 'notify' });
+ await ticks();
+ downloads[1](); // the repeat is stored with the old caption; the first delivery still downloads
+ await ticks();
+
+ events.handleMessagesUpsert({ messages: [edit()], type: 'notify' });
+ await ticks();
+
+ await expect(reply).resolves.toMatchObject({ id: 'R1' });
+ const [, , options] = sock.sendMessage.mock.calls[0] as [unknown, unknown, { quoted?: WAMessage }];
+ expect(options.quoted?.message?.imageMessage?.caption).toBe('fixed caption');
+ // The overlay is a copy: the stored row changes only once the first delivery settles.
+ expect(await caption()).toBe('about to be deleted');
+ downloads[0]();
+ await ticks();
+ expect(await caption()).toBe('fixed caption');
+ });
+
+ it('forgets the edit once the message is no longer in flight', async () => {
+ const { events } = build(() => undefined);
+ events.handleMessagesUpsert({ messages: [photo('TARGET')], type: 'notify' });
+ await ticks();
+ events.handleMessagesUpsert({ messages: [edit()], type: 'notify' });
+ await ticks();
+ expect(events.pendingEditOf('TARGET', photo('TARGET').key)).toBe('fixed caption');
+ downloads[0]();
+ await ticks();
+
+ // A later repeat is in flight again, but the store already carries the edit, and any newer one.
+ events.handleMessagesUpsert({ messages: [photo('TARGET')], type: 'notify' });
+ expect(events.pendingEditOf('TARGET', photo('TARGET').key)).toBeUndefined();
+ await ticks();
+ });
+
+ it('does not overlay an edit sent from another chat', async () => {
+ const { events } = build(() => undefined);
+ events.handleMessagesUpsert({ messages: [photo('TARGET')], type: 'notify' });
+ await ticks();
+ events.handleMessagesUpsert({ messages: [edit()], type: 'notify' });
+ await ticks();
+
+ const elsewhere = { ...photo('TARGET').key, remoteJid: '[email protected]' };
+ expect(events.pendingEditOf('TARGET', elsewhere)).toBeUndefined();
+ downloads[0]();
+ await ticks();
+ });
+
it('lets a delete for everyone win over an earlier edit', async () => {
const heard = jest.fn();
const { events } = build(heard);
diff --git a/src/engine/adapters/baileys-quoted-send.spec.ts b/src/engine/adapters/baileys-quoted-send.spec.ts
index 2ece41f0e..f3fe5c1bd 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,
wasDeletedForEveryone: () => false,
+ pendingEditOf: () => undefined,
markDeletedForEveryone: () => undefined,
putStoredMessage: () => undefined,
recordMessage: () => undefined,
diff --git a/src/engine/adapters/baileys-remaining-writes.spec.ts b/src/engine/adapters/baileys-remaining-writes.spec.ts
index 078051b34..2c954f814 100644
--- a/src/engine/adapters/baileys-remaining-writes.spec.ts
+++ b/src/engine/adapters/baileys-remaining-writes.spec.ts
@@ -42,6 +42,7 @@ function messaging(sock: Record<string, jest.Mock>, budgetMs: number): BaileysMe
loadLib: () => Promise.resolve({} as never),
getStoredMessage: () => Promise.resolve({ key: { ...LAST.key, fromMe: true }, message: {}, messageTimestamp: 1 }),
wasDeletedForEveryone: () => false,
+ pendingEditOf: () => undefined,
markDeletedForEveryone: () => undefined,
putStoredMessage: () => undefined,
recordLidMapping: () => undefined,
diff --git a/src/engine/adapters/baileys-sticker-webp.spec.ts b/src/engine/adapters/baileys-sticker-webp.spec.ts
index 8d8549d8f..bd49f1d0d 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),
wasDeletedForEveryone: () => false,
+ pendingEditOf: () => undefined,
markDeletedForEveryone: () => undefined,
putStoredMessage: () => undefined,
recordMessage: () => undefined,
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 719e19c14..ac88c5f1c 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -138,6 +138,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
this.config.messageStore?.update(this.config.dbSessionId, messageId, change),
wasDeletedForEveryone: messageId => this.events.wasDeletedForEveryone(messageId),
markDeletedForEveryone: messageId => this.events.markDeletedForEveryone(messageId),
+ pendingEditOf: (messageId, target) => this.events.pendingEditOf(messageId, target),
rememberOwnSend: id => this.ownSends.remember(id),
consumeOwnSend: id => this.ownSends.consume(id),
getOnMessage: () => this.callbacks.onMessage,
diff --git a/src/engine/adapters/create-call-link.spec.ts b/src/engine/adapters/create-call-link.spec.ts
index 245e63c23..2c9ff7653 100644
--- a/src/engine/adapters/create-call-link.spec.ts
+++ b/src/engine/adapters/create-call-link.spec.ts
@@ -47,6 +47,7 @@ describe('BaileysMessaging.createCallLink', () => {
} as never),
getStoredMessage: () => Promise.resolve(undefined),
wasDeletedForEveryone: () => false,
+ pendingEditOf: () => undefined,
markDeletedForEveryone: () => undefined,
putStoredMessage: () => undefined,
recordLidMapping: () => undefined,