Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
docs(comments): correct stale statements about the own-send echo
Yudhi Armyndharisebbee7562da6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a6f7c910c..3004f5ee2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Four contract corrections from a review of this cycle's own work** — the `409` description said the session had no engine when the guard actually fires on an engine that exists but is not `ready` (an unstarted session answers `400`); `send-bulk` declared a `409` it cannot produce, since the batch drains after the handler has answered `202`; the nine catalog and status routes declared that `409` but not the `404` their own service throws for an unstarted session; and the logout example showed a null `pushName` and `connectedAt` beside a populated `lastActive`, though logout clears only `phone`.+- **Fifteen statements in the codebase that were not true** — comments, a test name and an architecture sketch still described the own-send echo by its pre-0.10.0 behaviour: that whatsapp-web.js echoes carry no media, that the engines are at parity in carrying none, and that the echo never writes the database.+- **An API key's session allow-list showed ids that can never match** — `allowedSessions` is matched by exact equality against the session id, but the example was `['session-uuid-1', 'session-uuid-2']`, which would scope a key to nothing and deny every request. It now shows real UUIDs.- **Seven published examples showed values the API cannot produce** — a `sess_`-prefixed session id that `ParseUUIDPipe` rejects, two truncated UUIDs, a logout example missing the required `engineLoaded`, a readiness probe keyed on `database` rather than `mainDatabase`/`dataDatabase`, a `send-text` capability no engine declares, and the whatsapp-web.js id form on a Baileys-only route.diff --git a/dashboard/src/components/chats/ChatComposer.tsx b/dashboard/src/components/chats/ChatComposer.tsxindex 30c3fa820..2de44b983 100644--- a/dashboard/src/components/chats/ChatComposer.tsx+++ b/dashboard/src/components/chats/ChatComposer.tsx@@ -230,9 +230,9 @@ function ChatComposer({// Race guard: the realtime `message.sent` echo can arrive before this response and already// append the message by its real WA id (the dedup at receive time misses because the// optimistic placeholder still carries the temp id). If so, fold the placeholder INTO the- // echo's row via mergeOrAppend instead of just dropping it — the echo carries no media- // payload (engine parity marker), so dropping the placeholder would erase the attachment's- // base64 and leave a bare "📎 Media" bubble until the next refetch.+ // echo's row via mergeOrAppend instead of just dropping it — the echo may carry no media+ // payload (a Baileys API send echoes only a marker), so dropping the placeholder would erase+ // the attachment's base64 and leave a bare "📎 Media" bubble until the next refetch.const sendKey = messagesQueryKey(selectedSessionId, activeChat.id);queryClient.setQueryData<ChatMessageView[]>(sendKey, (prev = []) => {const reconciled: ChatMessageView = {diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.tsindex d7ddaa60c..7dc6b94c8 100644--- a/dashboard/src/utils/chatMessages.test.ts+++ b/dashboard/src/utils/chatMessages.test.ts@@ -152,7 +152,7 @@ test('mergeOrAppend keeps existing metadata when the incoming copy carries none'});test('mergeOrAppend: an omitted-media echo does NOT clobber the copy holding the payload', () => {- // The optimistic send bubble holds the only base64 copy; the engine's own-send echo carries just+ // The optimistic send bubble holds the only base64 copy; a Baileys API-send echo carries just// `{media: {omitted: true}}` (no data). Replacing wholesale would blank the sent image.const optimistic = msg({id: 'm-1',diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.tsindex 2e9e1d0a3..2f15902a4 100644--- a/dashboard/src/utils/chatMessages.ts+++ b/dashboard/src/utils/chatMessages.ts@@ -170,9 +170,9 @@ export function mergeReactionSnapshot(* Merge two metadata bags field-by-field. The incoming copy wins per field only when it actually* carries a value — a live `message.sent` echo is built as `{media, quotedMessage, call}` with* undefined leaves, and a wholesale `incoming ?? existing` swap would wipe the optimistic bubble's- * quote/call. Media has one extra rule: an incoming marker WITHOUT the payload (the engine's- * own-send echo and the media-less history fetch both emit `{media: {omitted: true}}` with no- * `data`) must not clobber an existing copy holding the real base64 — the optimistic send bubble is+ * quote/call. Media has one extra rule: an incoming marker WITHOUT the payload (a Baileys API-send+ * echo and the media-less history fetch both emit `{media: {omitted: true}}` with no `data`) must+ * not clobber an existing copy holding the real base64 — the optimistic send bubble is* the only copy with the payload until a refetch, and the cache is staleTime: Infinity.*/function mergeMessageMetadata(diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.mdindex 3937d1854..98b49437f 100644--- a/docs/03-system-architecture.md+++ b/docs/03-system-architecture.md@@ -1146,7 +1146,10 @@ export class BaileysAdapter implements IWhatsAppEngine {this.socket!.ev.on('messages.upsert', ({ messages }) => {for (const msg of messages) {- if (!msg.key.fromMe) this.callbacks.onMessage?.(this.toIncomingMessage(msg)); // neutral ids+ const incoming = this.toIncomingMessage(msg); // neutral ids+ // Own sends are not dropped: they route to onMessageCreate, which drives `message.sent`.+ if (msg.key.fromMe) this.callbacks.onMessageCreate?.(incoming);+ else this.callbacks.onMessage?.(incoming);}});}diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex d8ebdf674..8949b722d 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -724,8 +724,10 @@ export class BaileysEvents {return undefined;}- // The outbound "sent" echo passes skipMediaDownload: the sender already holds the media, and for- // parity with the wwjs message.sent (which carries no media buffer) we emit only the marker here.+ // The outbound "sent" echo passes skipMediaDownload: the API caller already holds the media and+ // the REST send path persists it, so re-downloading it here would buy nothing. This is where+ // Baileys deliberately diverges from wwjs, whose echo does download the payload+ // (wwebjs-message-events.ts) because a phone-composed send has no other source for it.if (skipMediaDownload || !isMediaDownloadEnabled()) {// Emit the omitted marker so the media field is present (webhook/n8n/dashboard contract).// mimetype is available pre-download from the message content.diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex ec2766263..6d3072397 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -441,7 +441,8 @@ 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 —- // best-effort and off the response path, with no media re-download (matching the wwjs payload).+ // 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);}return { id: sent?.key?.id ?? '', timestamp: this.host.toUnixSeconds(sent?.messageTimestamp) };diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 9b66b8fa3..2675b8016 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -493,9 +493,10 @@ export class BulkMessageService implements OnApplicationBootstrap {batch.progress.sent++;batch.progress.pending--;- // Persist like a single send so the message shows in chat history + stats. The engine echo- // (onMessageCreate) fires the webhook/WS but does NOT write the DB, so without this the- // bulk-sent message is invisible to the messages table.+ // Persist like a single send so the row carries the media payload and the batch's type+ // mapping — the engine echo (onMessageCreate) writes its own OUTGOING row, but only with what+ // the engine reported, and a Baileys API send echoes a media-less marker. The two writers+ // dedup on UNIQUE(sessionId, waMessageId).await this.persistSentMessage(batch.sessionId, msg.chatId, msg.type, content, messageResult);this.logger.debug(`Batch ${batch.batchId}: Sent message ${i + 1}/${batch.messages.length} to ${msg.chatId}`);diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 1aa32260e..6f41a54ec 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -1485,9 +1485,9 @@ describe('MessageService', () => {describe('persistSentState vs the own-send echo (dedup race)', () => {it('merges state onto the echo row, then drops the redundant PENDING row', async () => {// The engine's message_create echo (onMessageCreate) won the insert race, so the SENT-state save- // collides on UNIQUE(sessionId, waMessageId). The echo row carries only a media-less marker —- // the merge must land status/timestamp/metadata on it BEFORE the placeholder is deleted, or the- // payload is lost. The send still succeeds.+ // collides on UNIQUE(sessionId, waMessageId). The echo row carries only what the engine reported+ // — for a Baileys API send, a media-less marker — so the merge must land status/timestamp/metadata+ // on it BEFORE the placeholder is deleted, or the payload is lost. The send still succeeds.(repository.save as jest.Mock).mockImplementationOnce(msg => Promise.resolve(msg)) // saveOutgoingMessage (PENDING).mockRejectedValueOnce(new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'));diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 159e4f6d6..05b69cf0a 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -704,9 +704,10 @@ export class MessageService {} catch (persistError) {if (result.id && isUniqueConstraintError(persistError)) {// The engine's own-send echo (onMessageCreate) won the race and already persisted a row with- // this waMessageId. That row carries only a media-less marker — merge our SENT state AND our- // metadata (the actual media payload) onto it BEFORE dropping this redundant PENDING row, or- // the payload-bearing row is the one that gets deleted and the media is gone after a reload.+ // this waMessageId. That row carries only what the engine reported — for a Baileys API send,+ // a media-less marker — so merge our SENT state AND our metadata (the actual media payload)+ // onto it BEFORE dropping this redundant PENDING row, or the payload-bearing row is the one+ // that gets deleted and the media is gone after a reload.// Best-effort throughout: the send itself already succeeded.this.logger.debug(`Send echo already persisted ${result.id}; merging state and dropping the redundant pending row`,diff --git a/src/modules/session/message-row.mapper.spec.ts b/src/modules/session/message-row.mapper.spec.tsindex c521ecf64..22cf816ca 100644--- a/src/modules/session/message-row.mapper.spec.ts+++ b/src/modules/session/message-row.mapper.spec.ts@@ -40,8 +40,9 @@ describe('buildMessageMetadata', () => {});describe('omitted-media synthesis', () => {- // The wwjs own-send echo and the history backfill both lose the media payload; without a marker- // the row renders as an empty bubble and drops out of the by-type stats.+ // A wwjs own-send echo whose media download failed and the history backfill both arrive without+ // the payload; without a marker the row renders as an empty bubble and drops out of the by-type+ // stats.it.each([...MEDIA_MESSAGE_TYPES])('synthesizes a placeholder for a media-typed %s when asked', type => {expect(buildMessageMetadata(msg({ type: type as MessageType }), true)).toEqual({media: { mimetype: '', omitted: true },diff --git a/src/modules/session/message-row.mapper.ts b/src/modules/session/message-row.mapper.tsindex 92bd5c6c9..da231cdb0 100644--- a/src/modules/session/message-row.mapper.ts+++ b/src/modules/session/message-row.mapper.ts@@ -3,10 +3,11 @@ import type { IncomingMessage } from '../../engine/interfaces/whatsapp-engine.in/*** Message types whose rows must show a media placeholder even when the payload carried none.*- * The wwjs own-send echo carries no media field at all (Baileys emits an omitted marker), and the- * history sync maps messages media-free to keep its footprint down. Without the marker such a row- * renders as an empty bubble — the DB copy wins over the engine-history placeholder in the dashboard- * merge — and the by-type stats filter would skip it.+ * A wwjs own-send echo whose media download failed carries no media field at all, and the history+ * sync maps messages media-free to keep its footprint down. Without the marker such a row renders+ * as an empty bubble — the DB copy wins over the engine-history placeholder in the dashboard+ * merge — and the by-type stats filter would skip it. (The Baileys API-send echo needs no synthesis:+ * it emits the omitted marker itself.)*/export const MEDIA_MESSAGE_TYPES = new Set(['image', 'video', 'audio', 'voice', 'sticker', 'document']);@@ -18,7 +19,7 @@ export const OMITTED_MEDIA = { mimetype: '', omitted: true } as const;** The three persist paths (live inbound `onMessage`, own-send echo `onMessageCreate`, and the* pre-connection history backfill) each assembled this inline, with one deliberate difference:- * inbound trusts the engine's media field as-is, while the two paths that are known to lose media+ * inbound trusts the engine's media field as-is, while the two paths that can arrive without one* synthesize a placeholder. Keeping both rules in one function makes that difference explicit* instead of something to re-derive at each site.*diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex 1d827ee10..361574062 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -41,8 +41,9 @@ const isStatusSeedOnReadyEnabled = (): boolean => process.env.STATUS_SEED_ON_REA// Message types that carry downloadable media. Any persisted row of these types must have a media// marker in metadata — never NULL — or the dashboard renders an empty bubble (no placeholder) and the-// by-type stats filter skips the row. Sources that lack the payload (wwjs own-send echo, media-free-// history sync) get the omitted marker synthesized at the persistence chokepoints.+// by-type stats filter skips the row. Sources that arrive without a media field (media-free history+// sync, a wwjs own-send echo whose download failed) get the omitted marker synthesized at the+// persistence chokepoints.export interface ReconnectState extends ReconnectAttemptState {/** The pending attempt's timer. Lives here, not in the policy, which stays free of side effects. */diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 0886b91e3..0823b8075 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -3222,9 +3222,10 @@ describe('SessionService', () => {delete process.env.STORE_EPHEMERAL_MESSAGES;});- it('synthesizes the omitted media marker for a media echo carrying no media (wwjs shape)', async () => {- // wwjs' buildIncomingMessageBase never attaches media to the own-send echo; without the marker- // the dashboard renders an empty bubble and the by-type stats filter would skip the row.+ it('synthesizes the omitted media marker for a media echo carrying no media field', async () => {+ // A wwjs echo whose media download failed carries no media field at all — the sync+ // buildIncomingMessageBase attaches none and the enrichment around it is best-effort. Without+ // the marker the dashboard renders an empty bubble and the by-type stats filter would skip the row.const callbacks = await startAndCaptureCallbacks();(hookManager.execute as jest.Mock).mockImplementation((_e: string, data: unknown) =>Promise.resolve({ continue: true, data }),