Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): emit an in-flight message as its revoke or edit left it

Yudhi Armyndharis15c0bd00730a
diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.ts
index 8411be757..0a0c3a71c 100644
--- a/src/modules/session/message-projector.service.spec.ts
+++ b/src/modules/session/message-projector.service.spec.ts
@@ -930,6 +930,58 @@ describe('MessageProjector (inbound projection)', () => {
expect(afterB).toEqual([
[{ sessionId: SESSION_ID, waMessageId: 'B' }, expect.objectContaining({ type: 'revoked' })],
]);
+ // message.revoked already went out: B is not announced with the content its sender deleted.
+ expect(dispatched()).toEqual(['message.revoked:B', 'message.received:A']);
+ expect(eventsGateway.emitMessage.mock.calls.map(([, m]) => (m as { id: string }).id)).toEqual(['A']);
+ expect(automationRules.evaluateInbound.mock.calls.map(([, m]) => (m as { id: string }).id)).toEqual(['A']);
+ });
+
+ it('announces a message deleted for me while it waits for its turn as the revoked placeholder', async () => {
+ const engine = makeEngine();
+ engines.set(SESSION_ID, engine);
+ const release = holdHooks();
+
+ projector.handleInboundMessage(SESSION_ID, engine, makeIncoming({ id: 'A', chatId: chatA }));
+ const b = makeIncoming({ id: 'B', chatId: chatA, body: 'secret', quotedMessage: { id: 'Q', body: 'quoted' } });
+ projector.handleInboundMessage(SESSION_ID, engine, b);
+ release.get('B')!();
+ await flush();
+ // The REST delete-for-me: no engine revoke event follows, so no message.revoked went out.
+ void projector.recordRevoke(SESSION_ID, 'B');
+ release.get('A')!();
+ await flush();
+
+ expect(dispatched()).toEqual(['message.received:A', 'message.received:B']);
+ const announcedB = (webhookService.dispatch.mock.calls as unknown[][]).at(-1)![2] as Record<string, unknown>;
+ expect(announcedB).toMatchObject({ id: 'B', body: '', type: 'revoked' });
+ expect(announcedB).not.toHaveProperty('quotedMessage');
+ expect(eventsGateway.emitMessage).toHaveBeenLastCalledWith(SESSION_ID, announcedB);
+ expect(automationRules.evaluateInbound).toHaveBeenLastCalledWith(SESSION_ID, announcedB);
+ });
+
+ it('announces a message edited while it waits for its turn with the edited body', async () => {
+ Object.assign(eventsGateway, { emitMessageEdited: jest.fn() });
+ const engine = makeEngine();
+ engines.set(SESSION_ID, engine);
+ const release = holdHooks();
+
+ projector.handleInboundMessage(SESSION_ID, engine, makeIncoming({ id: 'A', chatId: chatA }));
+ projector.handleInboundMessage(SESSION_ID, engine, makeIncoming({ id: 'B', chatId: chatA, body: 'typo' }));
+ release.get('B')!();
+ await flush();
+ projector.applyMessageEditQueued(SESSION_ID, { messageId: 'B', body: 'fixed' } as never);
+ release.get('A')!();
+ await flush();
+
+ expect(webhookService.dispatch).toHaveBeenCalledWith(
+ SESSION_ID,
+ 'message.received',
+ expect.objectContaining({ id: 'B', body: 'fixed' }),
+ );
+ expect(eventsGateway.emitMessage).toHaveBeenLastCalledWith(
+ SESSION_ID,
+ expect.objectContaining({ body: 'fixed' }),
+ );
});
it('orders an own-send echo after an earlier inbound message of the same chat', async () => {
@@ -983,6 +1035,8 @@ describe('MessageProjector (inbound projection)', () => {
expect(inserted()).toEqual(['A', 'S']);
expect(updatesAfterS()).toEqual([[whereS, expect.objectContaining({ body: '', type: 'revoked' })]]);
+ expect(dispatched()).toEqual(['message.revoked:S', 'message.received:A']);
+ expect(eventsGateway.emitMessageSent).not.toHaveBeenCalled();
});
it('writes an edit onto the echo row once it is written', async () => {
@@ -992,6 +1046,11 @@ describe('MessageProjector (inbound projection)', () => {
await flush();
expect(updatesAfterS()).toEqual([[whereS, { body: 'fixed' }]]);
+ expect(webhookService.dispatch).toHaveBeenCalledWith(
+ SESSION_ID,
+ 'message.sent',
+ expect.objectContaining({ id: 'S', body: 'fixed' }),
+ );
});
it('advances the echo row to the furthest ack that arrived before it was written', async () => {
@@ -1011,6 +1070,11 @@ describe('MessageProjector (inbound projection)', () => {
await flush();
expect(updatesAfterS()).toEqual([[whereS, expect.objectContaining({ body: '', type: 'revoked' })]]);
+ expect(webhookService.dispatch).toHaveBeenCalledWith(
+ SESSION_ID,
+ 'message.sent',
+ expect.objectContaining({ id: 'S', body: '', type: 'revoked' }),
+ );
});
it('writes a REST edit onto the echo row once it is written', async () => {
diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.ts
index a0c4ead2a..3a3c6218e 100644
--- a/src/modules/session/message-projector.service.ts
+++ b/src/modules/session/message-projector.service.ts
@@ -130,6 +130,8 @@ export class MessageProjector {
{
message: InboundMessageData;
revoked?: boolean;
+ // Set when the revoke came from the engine, so message.revoked went out for it.
+ revokeAnnounced?: boolean;
editedBody?: string;
ackStatus?: MessageStatus;
// Latest reaction per sender; '' means the sender withdrew theirs.
@@ -228,8 +230,8 @@ export class MessageProjector {
/** Record a message as not yet written; a re-fire of the same id keeps the changes recorded so far. */
private trackInFlight(key: string, message: InboundMessageData) {
- const { revoked, editedBody, ackStatus, reactions } = this.inboundInFlight.get(key) ?? {};
- const inFlight = { message, revoked, editedBody, ackStatus, reactions };
+ const { revoked, revokeAnnounced, editedBody, ackStatus, reactions } = this.inboundInFlight.get(key) ?? {};
+ const inFlight = { message, revoked, revokeAnnounced, editedBody, ackStatus, reactions };
this.inboundInFlight.set(key, inFlight);
return inFlight;
}
@@ -589,13 +591,35 @@ export class MessageProjector {
void this.chatMediaArchive?.archive(dbMessage).catch(() => undefined);
}
+ const announced = this.withChangesMadeInFlight(id, finalMessage);
+ if (!announced) return;
// Dispatch to webhooks with potentially modified message
- void this.webhookService.dispatch(id, 'message.received', finalMessage);
+ void this.webhookService.dispatch(id, 'message.received', announced);
// Autoreply rules ride the same at-most-once dispatch (the insert oracle above dedupes engine
// re-fires) and stay fail-open like the webhook: a broken rule must never break the receive path.
- void this.automationRules?.evaluateInbound(id, finalMessage).catch(() => undefined);
+ void this.automationRules?.evaluateInbound(id, announced).catch(() => undefined);
// Emit real-time event to WebSocket clients
- this.eventsGateway.emitMessage(id, finalMessage);
+ this.eventsGateway.emitMessage(id, announced);
+ }
+
+ /**
+ * The message as a revoke or edit that arrived while it was in flight left it, for its announcement:
+ * null once the engine revoked it (message.revoked already went out, so the deleted content is not
+ * announced after it), the revoked placeholder when only the REST delete did (a delete-for-me emits no
+ * engine revoke, and the message still exists for its sender), the edited body when edited
+ * (message.edited already went out with it). The stored row takes the same changes in
+ * {@link applyChangesMadeInFlight}.
+ */
+ private withChangesMadeInFlight(id: string, message: InboundMessageData): InboundMessageData | null {
+ const pending = this.inboundInFlight.get(`${id}:${message.id}`);
+ if (pending?.revokeAnnounced) return null;
+ if (pending?.revoked) {
+ // Nothing of the content survives, as in REVOKED_ROW_PATCH.
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { media, quotedMessage, call, buttons, button, location, order, product, mentionedIds, ...kept } = message;
+ return { ...kept, body: '', type: 'revoked' };
+ }
+ return pending?.editedBody === undefined ? message : { ...message, body: pending.editedBody };
}
/** Engine callback body, lifted out of initializeEngine so the wiring table stays readable. */
@@ -733,9 +757,11 @@ export class MessageProjector {
}
}
- void this.webhookService.dispatch(id, 'message.sent', finalMessage);
+ const announced = this.withChangesMadeInFlight(id, finalMessage);
+ if (!announced) return;
+ void this.webhookService.dispatch(id, 'message.sent', announced);
// Emit real-time event to WebSocket clients (as message.sent, not message.received)
- this.eventsGateway.emitMessageSent(id, finalMessage);
+ this.eventsGateway.emitMessageSent(id, announced);
}
/** Engine callback body, lifted out of initializeEngine so the wiring table stays readable. */
@@ -857,6 +883,8 @@ export class MessageProjector {
// `revokedId` falls back to `id` (Baileys, where the two are the same).
const revokedWaMessageId = message.revokedId ?? message.id;
void this.recordRevoke(id, revokedWaMessageId);
+ const inFlight = this.inboundInFlight.get(`${id}:${revokedWaMessageId}`);
+ if (inFlight) inFlight.revokeAnnounced = true;
// Notify consumers regardless of whether the row existed: webhook (message.revoked
// is a declared event) + the real-time dashboard stream.