Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): ignore paged-in history when recovering a wwjs forward id

Yudhi Armyndharis42cb60f00674
diff --git a/src/engine/adapters/wwebjs-forward-recovery.spec.ts b/src/engine/adapters/wwebjs-forward-recovery.spec.ts
new file mode 100644
index 000000000..e54bf0275
--- /dev/null
+++ b/src/engine/adapters/wwebjs-forward-recovery.spec.ts
@@ -0,0 +1,58 @@
+import type { Client } from 'whatsapp-web.js';
+import { WwebjsMessaging } from './wwebjs-messaging';
+import { createLogger } from '../../common/services/logger.service';
+import { type WwebjsEngineHost } from './wwebjs-host';
+
+/**
+ * forwardMessage recovers the copy's id by diffing the destination chat's loaded own messages before
+ * and after the send. Those reads take no limit, so they return everything WhatsApp Web holds, and a
+ * concurrent call on the same chat (a history read, a reply) can page older messages in between the
+ * two reads. Those arrive older than anything the first read saw and must not count as new.
+ */
+const logger = createLogger('wwebjs-forward-recovery.spec');
+
+const row = (id: string, timestamp: number, isForwarded = false) => ({
+ id: { _serialized: id },
+ timestamp,
+ isForwarded,
+});
+
+async function forwardWith(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 host = {
+ ensureReady: jest.fn(),
+ ensureNotChannelRecipient: jest.fn(),
+ getClient: () => client as unknown as Client,
+ getNumberId: jest.fn().mockResolvedValue(undefined),
+ isPageTransportError: () => false,
+ reportIfPageTransportError: jest.fn(),
+ config: {},
+ logger,
+ } as unknown as WwebjsEngineHost;
+ const result = await new WwebjsMessaging(host).forwardMessage('[email protected]', '[email protected]', 'SRC1');
+ expect(forward).toHaveBeenCalledWith('[email protected]');
+ return result.id;
+}
+
+describe('WwebjsMessaging.forwardMessage id recovery with history paged in meanwhile', () => {
+ // Returning OLD here would write another message's id onto the forward's row.
+ it('does not take an older forwarded message for the copy', async () => {
+ expect(await forwardWith([row('TEXT', 1000)], [row('OLD', 500, true), row('TEXT', 1000), row('FWD', 1000)])).toBe(
+ 'FWD',
+ );
+ });
+
+ it('still identifies the copy when older own messages were paged in', async () => {
+ expect(
+ await forwardWith(
+ [row('TEXT', 1000)],
+ [row('OLD1', 400, true), row('OLD2', 500), row('TEXT', 1000), row('FWD', 1001, true)],
+ ),
+ ).toBe('FWD');
+ });
+});
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index 81e750fb8..aca7272a0 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -634,13 +634,19 @@ export class WwebjsMessaging {
// the forwarded copy from an earlier send with the same whole-second timestamp. Only messages
// WhatsApp Web already holds are read, so this never pages the chat's history in ahead of the
// send. A failed read never blocks the forward; it only leaves the copy unidentified.
+ // The newest timestamp it saw is kept too: a concurrent call on the destination chat can page
+ // older history in before the second read, and those messages are older than every one loaded.
let resolvedTo = toChatId;
- let before = undefined as Set<string> | undefined;
+ let before = undefined as { ids: Set<string>; newest: number } | undefined;
await this.sendResolved(toChatId, async to => {
resolvedTo = to;
before = undefined;
try {
- before = new Set((await this.loadedOwnMessages(to)).map(m => toMessageResult(m).id));
+ const snapshot = await this.loadedOwnMessages(to);
+ before = {
+ ids: new Set(snapshot.map(m => toMessageResult(m).id)),
+ newest: snapshot.reduce((newest, m) => Math.max(newest, m.timestamp), 0),
+ };
} catch (error) {
this.host.logger.warn(`Could not read the destination chat before forwarding: ${String(error)}`);
}
@@ -661,7 +667,7 @@ export class WwebjsMessaging {
const known = before;
const fresh = (await this.loadedOwnMessages(resolvedTo)).filter(m => {
const id = toMessageResult(m).id;
- return id !== '' && !known.has(id);
+ return id !== '' && !known.ids.has(id) && m.timestamp >= known.newest;
});
const forwarded = fresh.filter(m => m.isForwarded);
const sent = fresh.length === 1 ? fresh[0] : forwarded.length === 1 ? forwarded[0] : undefined;