Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwebjs): stop a forward from returning another message's id

Yudhi Armyndharisf857d6428fde
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index a385a859a..02d73f315 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -1036,10 +1036,13 @@ describe('WhatsAppWebJsAdapter.forwardMessage (returns the real sent id, not a s
const forward = jest.fn().mockResolvedValue(undefined);
const sourceChat = { fetchMessages: jest.fn().mockResolvedValue([{ id: { _serialized: 'SRC1' }, forward }]) };
const destChat = {
- fetchMessages: jest.fn().mockResolvedValue([
- { id: { _serialized: 'OLD' }, timestamp: 100 },
- { id: { _serialized: 'REAL_FWD' }, timestamp: 200 }, // most recent fromMe = the forwarded copy
- ]),
+ fetchMessages: jest
+ .fn()
+ .mockResolvedValueOnce([{ id: { _serialized: 'OLD' }, timestamp: 100 }]) // read before the forward
+ .mockResolvedValueOnce([
+ { id: { _serialized: 'OLD' }, timestamp: 100 },
+ { id: { _serialized: 'REAL_FWD' }, timestamp: 200 }, // the one new fromMe = the forwarded copy
+ ]),
};
const client = {
getChatById: jest.fn((id: string) => Promise.resolve(id === '[email protected]' ? destChat : sourceChat)),
@@ -1082,6 +1085,58 @@ describe('WhatsAppWebJsAdapter.forwardMessage (returns the real sent id, not a s
expect(forward).toHaveBeenCalledWith('[email protected]');
expect(result.id).toBe('');
});
+
+ // Destination reads: the first call is the snapshot taken before the forward, the second the read
+ // after it. Timestamps are whole seconds, so a send just before the forward can share one.
+ const forwardWith = async (beforeRows: unknown[], afterRows: unknown[]): Promise<string> => {
+ const forward = jest.fn().mockResolvedValue(undefined);
+ const sourceChat = { fetchMessages: jest.fn().mockResolvedValue([{ id: { _serialized: 'SRC1' }, forward }]) };
+ const destChat = { fetchMessages: jest.fn().mockResolvedValueOnce(beforeRows).mockResolvedValueOnce(afterRows) };
+ const client = {
+ getChatById: jest.fn((id: string) => Promise.resolve(id === '[email protected]' ? destChat : sourceChat)),
+ };
+ const result = await readyAdapter(client).forwardMessage('[email protected]', '[email protected]', 'SRC1');
+ expect(forward).toHaveBeenCalledWith('[email protected]');
+ return result.id;
+ };
+ const row = (id: string, isForwarded = false) => ({ id: { _serialized: id }, timestamp: 1000, isForwarded });
+
+ it('returns the new copy, not an earlier send that landed in the same second', async () => {
+ // Order matters: the earlier send comes last, where a latest-timestamp pick would keep it.
+ expect(await forwardWith([row('TEXT')], [row('FWD'), row('TEXT')])).toBe('FWD');
+ });
+
+ it('returns the unknown id when nothing new appears in the destination chat', async () => {
+ expect(await forwardWith([row('TEXT')], [row('TEXT')])).toBe('');
+ });
+
+ it('returns the unknown id when several new messages appear and none, or more than one, is marked forwarded', async () => {
+ expect(await forwardWith([row('TEXT')], [row('TEXT'), row('A'), row('B')])).toBe('');
+ expect(await forwardWith([], [row('A', true), row('B', true)])).toBe('');
+ });
+
+ it('picks the one marked forwarded when a concurrent send also appeared', async () => {
+ expect(await forwardWith([row('TEXT')], [row('TEXT'), row('OTHER'), row('FWD', true)])).toBe('FWD');
+ });
+
+ it('still forwards, with the unknown id, when the destination cannot be read beforehand', async () => {
+ const forward = jest.fn().mockResolvedValue(undefined);
+ const sourceChat = { fetchMessages: jest.fn().mockResolvedValue([{ id: { _serialized: 'SRC1' }, forward }]) };
+ const destChat = {
+ fetchMessages: jest
+ .fn()
+ .mockRejectedValueOnce(new Error('Evaluation failed'))
+ .mockResolvedValueOnce([row('FWD', true)]),
+ };
+ const client = {
+ getChatById: jest.fn((id: string) => Promise.resolve(id === '[email protected]' ? destChat : sourceChat)),
+ };
+
+ const result = await readyAdapter(client).forwardMessage('[email protected]', '[email protected]', 'SRC1');
+
+ expect(forward).toHaveBeenCalledWith('[email protected]');
+ expect(result.id).toBe('');
+ });
});
describe('WhatsAppWebJsAdapter channels (#625 — wwebjs Client has no getChannelById)', () => {
@@ -4737,12 +4792,18 @@ describe('LID resolution for individual sends (#573 — WhatsApp @c.us → @lid
const forward = jest.fn().mockResolvedValue(undefined);
const srcMsg = { id: { _serialized: 'M1' }, forward };
const srcChat = { fetchMessages: jest.fn().mockResolvedValue([srcMsg]) };
- const destChat = { fetchMessages: jest.fn().mockResolvedValue([{ id: { _serialized: 'OUT1' }, timestamp: 123 }]) };
- const getChatById = jest.fn().mockResolvedValueOnce(srcChat).mockResolvedValueOnce(destChat);
+ const destChat = {
+ fetchMessages: jest
+ .fn()
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([{ id: { _serialized: 'OUT1' }, timestamp: 123 }]),
+ };
+ const getChatById = jest.fn().mockResolvedValueOnce(srcChat).mockResolvedValue(destChat);
const getNumberId = jest.fn().mockResolvedValue({ _serialized: '159442138038327@lid' });
const res = await ready({ getChatById, getNumberId }).forwardMessage('[email protected]', '[email protected]', 'M1');
expect(forward).toHaveBeenCalledWith('159442138038327@lid');
expect(getChatById).toHaveBeenNthCalledWith(2, '159442138038327@lid');
+ expect(getChatById).toHaveBeenNthCalledWith(3, '159442138038327@lid');
expect(res.id).toBe('OUT1');
});
});
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index 1a32894c7..110e1fe7c 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -620,32 +620,44 @@ export class WwebjsMessaging {
// The forward's send leg fails with `No LID for user` for a LID-migrated destination, so resolve
// it (and self-heal a stale mapping) via sendResolved. Capture the id actually sent to so the
// id-recovery below reads back from the SAME (resolved) chat, not the raw @c.us (#583 R1).
+ // The ids already in that chat are read first, on every attempt, so the recovery below can tell
+ // the forwarded copy from an earlier send with the same whole-second timestamp. A failed read
+ // never blocks the forward; it only leaves the copy unidentified.
let resolvedTo = toChatId;
- await this.sendResolved(toChatId, to => {
+ let before = undefined as Set<string> | undefined;
+ await this.sendResolved(toChatId, async to => {
resolvedTo = to;
+ before = undefined;
+ try {
+ before = new Set((await this.recentOwnMessages(to)).map(m => toMessageResult(m).id));
+ } catch (error) {
+ this.host.logger.warn(`Could not read the destination chat before forwarding: ${String(error)}`);
+ }
return msgToForward.forward(to);
});
// whatsapp-web.js's forward() returns void, so BEST-EFFORT recover the REAL id of the sent copy by
- // reading it back from the destination chat (the most recent outgoing message). The delivery-ack
- // matcher keys on this id, so a synthetic one would leave the forward stuck at SENT; Baileys already
+ // reading it back from the destination chat: the one outgoing message that was not there before
+ // the forward, or, when several appeared, the only one marked forwarded. The delivery-ack matcher
+ // keys on this id, so a synthetic one would leave the forward stuck at SENT; Baileys already
// returns the real id. The forward already succeeded here, so recovery must NEVER fail the operation.
- // When the copy can't be identified we return an explicit-unknown id (empty): message.service then
- // leaves the row's waMessageId unset so no ack can mis-match it — unlike a synthetic or source id,
- // which could cross-drive another row's delivery status. Concurrent forwards to the same chat may
- // mis-identify the copy — acceptable for delivery-status accuracy.
+ // When the copy can't be identified (no snapshot, or no single candidate, as with two forwards
+ // to the same chat at once) we return an explicit-unknown id (empty): message.service then
+ // leaves the row's waMessageId unset so no ack can mis-match it. A wrong id is worse: persisting
+ // it merges the forward's row into the other message's.
try {
- const destChat = await this.client().getChatById(resolvedTo);
- const sentByMe = (await destChat?.fetchMessages({ limit: 5, fromMe: true })) ?? [];
- let sent: (typeof sentByMe)[number] | undefined;
- for (const m of sentByMe) {
- if (!sent || m.timestamp > sent.timestamp) {
- sent = m;
+ if (before) {
+ const known = before;
+ const fresh = (await this.recentOwnMessages(resolvedTo)).filter(m => {
+ const id = toMessageResult(m).id;
+ return id !== '' && !known.has(id);
+ });
+ const forwarded = fresh.filter(m => m.isForwarded);
+ const sent = fresh.length === 1 ? fresh[0] : forwarded.length === 1 ? forwarded[0] : undefined;
+ if (sent) {
+ return toMessageResult(sent);
}
}
- if (sent) {
- return toMessageResult(sent);
- }
} catch (error) {
// Still surface a dead page even though the send itself succeeded (detection only; the
// forward's best-effort recovery contract is unchanged).
@@ -659,6 +671,12 @@ export class WwebjsMessaging {
}
}
+ /** The last few messages this account sent to a chat, in the order whatsapp-web.js returns them. */
+ private async recentOwnMessages(chatId: string): Promise<Message[]> {
+ const chat = await this.client().getChatById(chatId);
+ return (await chat?.fetchMessages({ limit: 5, fromMe: true })) ?? [];
+ }
+
async reactToMessage(chatId: string, messageId: string, emoji: string): Promise<void> {
this.host.ensureReady();
await this.withPage('reactToMessage', async () => {