Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(chats): persist and display edited message indicator
yederlvf1db933f4b21
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 991e89208..f65653ec3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -33,6 +33,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Show a localized edited indicator in Chats for observed message edits, including after a reload (#1905).+- Keep deleted sessions free of late message, status and bulk writes.- Retain sending limits while hooks or preparation are pending, including across UTC midnight.- Preserve whatsapp-web.js readiness when an earlier QR render completes.diff --git a/dashboard/src/components/chats/ChatThread.test.ts b/dashboard/src/components/chats/ChatThread.test.tsindex 7a61796e6..8bfe3d374 100644--- a/dashboard/src/components/chats/ChatThread.test.ts+++ b/dashboard/src/components/chats/ChatThread.test.ts@@ -1821,3 +1821,20 @@ test('focus that arrives by keyboard clears the pointer mark a click left, and abubble.focus();assert.equal(thread.hasAttribute('data-pointer'), false);});++test('shows the edited indicator for a persisted message and keeps it after remount', () => {+ const message = { ...PROMPT, metadata: { edited: true } };+ const { container } = renderThread('viewer', [message]);+ assert.equal(container.querySelector('.message-edited')?.textContent, 'Edited');+ rtl.cleanup();+ const reloaded = renderThread('viewer', [JSON.parse(JSON.stringify(message)) as ChatMessageView]);+ assert.equal(reloaded.container.querySelector('.message-edited')?.textContent, 'Edited');+});++test('does not label an unedited or revoked message as edited', () => {+ const { container } = renderThread('viewer', [+ { ...PROMPT, metadata: undefined },+ { ...PROMPT, id: 'revoked', waMessageId: 'revoked', type: 'revoked', metadata: { edited: true } },+ ]);+ assert.equal(container.querySelector('.message-edited'), null);+});diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsxindex f7171acb1..3b771125b 100644--- a/dashboard/src/components/chats/ChatThread.tsx+++ b/dashboard/src/components/chats/ChatThread.tsx@@ -741,6 +741,7 @@ function ChatThread({)}<div className="message-meta">+ {!isRevoked && msg.metadata?.edited && <span className="message-edited">{t('chats.edited')}</span>}<span className="message-time">{formattedTime}</span>{/* delivered and read render the SAME glyph and differ only in colour, whichcarries the meaning nowhere a screen reader or a colour-blind reader candiff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 80c11c30a..1e19c5ea7 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -80,6 +80,7 @@"logs": "السجلات"},"chats": {+ "edited": "تم التعديل","media": {"location": "الموقع","call": "مكالمة",diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex a6c9752ab..eebe8f0c0 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -72,6 +72,7 @@"logs": "Protokolle"},"chats": {+ "edited": "Bearbeitet","media": {"location": "Standort","call": "Anruf",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 8ad0f95f6..8efd90c67 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -72,6 +72,7 @@"logs": "Logs"},"chats": {+ "edited": "Edited","media": {"location": "Location","call": "Call",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 7ae4ce483..565789835 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -74,6 +74,7 @@"templates": "Plantillas"},"chats": {+ "edited": "Editado","media": {"location": "Ubicación","call": "Llamada",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex 13bfa9a28..7879c7087 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -74,6 +74,7 @@"logs": "Journaux"},"chats": {+ "edited": "Modifié","media": {"location": "Localisation","call": "Appel",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 0530ca8eb..1ad4558d8 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -76,6 +76,7 @@"logs": "לוגים"},"chats": {+ "edited": "נערך","media": {"location": "מיקום","call": "שיחה",diff --git a/dashboard/src/i18n/locales/hi.json b/dashboard/src/i18n/locales/hi.jsonindex 06cb553ba..5a758e4a3 100644--- a/dashboard/src/i18n/locales/hi.json+++ b/dashboard/src/i18n/locales/hi.json@@ -72,6 +72,7 @@"logs": "लॉग्स"},"chats": {+ "edited": "संपादित","media": {"location": "स्थान","call": "कॉल",diff --git a/dashboard/src/i18n/locales/id.json b/dashboard/src/i18n/locales/id.jsonindex 9ed33737d..babb77c10 100644--- a/dashboard/src/i18n/locales/id.json+++ b/dashboard/src/i18n/locales/id.json@@ -72,6 +72,7 @@"logs": "Log"},"chats": {+ "edited": "Diedit","media": {"location": "Lokasi","call": "Panggilan",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 9cf97d0b5..044dd751b 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -74,6 +74,7 @@"logs": "Log"},"chats": {+ "edited": "Modificato","media": {"location": "Posizione","call": "Chiamata",diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex c6dafc09a..154236e46 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -72,6 +72,7 @@"logs": "로그"},"chats": {+ "edited": "수정됨","media": {"location": "위치","call": "통화",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 90c17c8cf..35b3a29bf 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -74,6 +74,7 @@"templates": "Modelos"},"chats": {+ "edited": "Editado","media": {"location": "Localização","call": "Chamada",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex e79c9adcd..296860d10 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -72,6 +72,7 @@"logs": "లాగ్స్"},"chats": {+ "edited": "సవరించబడింది","media": {"location": "స్థానం","call": "కాల్",diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex 114672e8f..bf3699278 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -72,6 +72,7 @@"logs": "Kayıtlar (Logs)"},"chats": {+ "edited": "Düzenlendi","media": {"location": "Konum","call": "Arama",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex 8367d2cf6..dce01be63 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -72,6 +72,7 @@"logs": "日志"},"chats": {+ "edited": "已编辑","media": {"location": "位置","call": "通话",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 441df236f..c9135d331 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -72,6 +72,7 @@"logs": "記錄"},"chats": {+ "edited": "已編輯","media": {"location": "位置","call": "通話",diff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.cssindex d5f2dc8e7..9ff70e4b8 100644--- a/dashboard/src/pages/Chats.css+++ b/dashboard/src/pages/Chats.css@@ -731,6 +731,7 @@margin-top: 0.25rem;}+.chats-page .message-edited,.chats-page .message-time {font-size: 0.6875rem;color: var(--text-muted);@@ -738,6 +739,7 @@/* A styled status bubble sets its own inline background + white text; let its timestamp inheritinstead of staying the muted gray meant for the default bubble. */+.chats-page .message-bubble[style] .message-edited,.chats-page .message-bubble[style] .message-time {color: inherit;opacity: 0.75;diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 245c214f4..c603e234a 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -329,6 +329,8 @@ export interface ChatMessage {};quotedMessage?: { id: string; body: string };reactions?: Record<string, string>;+ /** The gateway observed an edit of this message. */+ edited?: boolean;call?: { video: boolean; missed: boolean };/** Business prompt choices (Baileys). Present on inbound prompts that offer buttons. */buttons?: Array<{ id: string; text: string }>;diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.tsindex c0a8b8ef2..b1f307eea 100644--- a/dashboard/src/utils/chatMessages.test.ts+++ b/dashboard/src/utils/chatMessages.test.ts@@ -769,3 +769,26 @@ test('mergeDeliveryStatus: a late lower tick never downgrades the shown one, andassert.equal(mergeDeliveryStatus('sent', 'failed'), 'failed');assert.equal(mergeDeliveryStatus('failed', 'read'), 'failed');});++test('applyMessageEdit marks the message and preserves reactions and media', () => {+ const metadata = { reactions: { alice: '👍' }, media: { mimetype: 'image/jpeg', data: 'test' } };+ const before = [msg({ id: 'edited', metadata })];+ const after = applyMessageEdit(before, { messageId: 'edited', body: 'new caption' });+ assert.deepEqual(after[0].metadata, { ...metadata, edited: true });+ assert.deepEqual(before[0].metadata, metadata);+});++test('applyMessageEdit cannot mark or restore a revoked message', () => {+ const before = [msg({ id: 'revoked', type: 'revoked', body: '' })];+ assert.equal(applyMessageEdit(before, { messageId: 'revoked', body: 'late edit' }), before);+});++test('a later message echo preserves the edited marker', () => {+ const before = [msg({ id: 'edited', waMessageId: 'edited', metadata: { edited: true } })];+ const after = mergeOrAppend(+ before,+ msg({ id: 'edited', waMessageId: 'edited', metadata: { reactions: { alice: '👍' } } }),+ );+ assert.equal(after[0].metadata?.edited, true);+ assert.deepEqual(after[0].metadata?.reactions, { alice: '👍' });+});diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.tsindex bac38e76b..bb849aa83 100644--- a/dashboard/src/utils/chatMessages.ts+++ b/dashboard/src/utils/chatMessages.ts@@ -249,6 +249,7 @@ export interface ChatMessageView extends ChatMessage {media?: MessageMedia;quotedMessage?: { id: string; body: string };reactions?: Record<string, string>;+ edited?: boolean;call?: { video: boolean; missed: boolean };buttons?: Array<{ id: string; text: string }>;poll?: { name: string; options: string[]; allowMultipleAnswers: boolean };@@ -336,6 +337,7 @@ function mergeMessageMetadata(return incoming.media;})();const merged: NonNullable<ChatMessageView['metadata']> = {};+ if (existing.edited || incoming.edited) merged.edited = true;if (media) merged.media = media;const quotedMessage = incoming.quotedMessage ?? existing.quotedMessage;if (quotedMessage) merged.quotedMessage = quotedMessage;@@ -470,6 +472,6 @@ export function applyMessageEdit(const idx = list.findIndex(byMessageId(event.messageId));if (idx === -1 || list[idx].type === 'revoked') return list;const next = list.slice();- next[idx] = { ...next[idx], body: event.body };+ next[idx] = { ...next[idx], body: event.body, metadata: { ...next[idx].metadata, edited: true } };return next;}diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 5d9356a6e..ace4a229e 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1380,6 +1380,8 @@ GET /api/sessions/:sessionId/messages?since=1789855200000&until=1789941600000&orEach `Message`: `{ id (uuid), sessionId, waMessageId (string|null), chatId, from, to, chatName (string|null; the sender's push name, or their saved contact name when no push name was reported), author (string|null; the real sender of a group, status or broadcast-list message, where from holds the group, status@broadcast or list id; on Baileys a list message the account received is filed under the sender, so from is the sender too), body (string|null), type, direction ('incoming'|'outgoing'), timestamp (number|null), metadata (object|null), mediaPath (string|null; storage key of archived media), mediaMimetype (string|null), status ('pending'|'sent'|'delivered'|'read'|'failed'), createdAt (ISO date) }`. By default, ordered by `createdAt` DESC, then by a dialect-dependent second key. The tiebreaker matters: `createdAt` is not unique (SQLite stores whole seconds, a PostgreSQL bulk write ties every row it inserts, and a history backfill carries WhatsApp's own second-resolution timestamp), and without a total order two pages of one walk can repeat a row and omit another. On SQLite the second key is `rowid`, the stored insertion sequence, so messages sharing a second come back in the order they arrived. PostgreSQL has no equivalent (`ctid` moves on every ack update), so it keeps `id`, a random uuid: the walk is equally correct there, but a same-second group is not in arrival order. Note that `offset` still addresses a position by count, so a list taking concurrent writes can shift under a walk: a message arriving mid-walk pushes every older row down one, and the next page re-serves a row the previous one already returned. Pass `after` instead to walk a live chat safely; it anchors on the last row you received, which an arriving message cannot move. The response is the raw service object (no envelope). Unlike the live `IncomingMessage` shape below, this persisted `Message` does **not** carry `kind` — re-derive the chat kind from `chatId` (see `ChatKind` / `chatKind()`) if needed. When present, `metadata` may include `media`, `quotedMessage`, `call`, `reactions`, `poll { name, options, allowMultipleAnswers }` for a poll creation message, and, for Baileys inbound business prompts, `buttons: [{ id, text }, …]` so a client (including the dashboard Chats thread) can re-render the choices after reload and tap them via [`POST .../click-button`](#post-apisessionssessionidmessagesclick-button).+For messages whose edits the gateway observes, `metadata.edited` is `true`. Chats displays a localized edited indicator for these messages, including after reloading. Existing messages are not retroactively marked, and a deleted message keeps its deleted placeholder instead. The `message.edited` event payload is unchanged.+> **Inline media is carried up to a budget, then omitted.** `MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default) bounds how much inline media one response may hold across its rows. A row is not a bounded object, `limit` is clamped to `[1,100]` but each row can carry its base64 in `metadata.media.data`, so a page of media rows could otherwise reach hundreds of megabytes and fail the read outright. The budget is spent newest-first, matching the selected descending order, so a page that cannot carry everything keeps the most recent media. Past it a payload is replaced with `{ mimetype, filename?, omitted: true, sizeBytes }`, the same marker the engine emits for inbound media over `MEDIA_DOWNLOAD_MAX_BYTES`, and the bytes remain available from [`GET /messages/:chatId/:messageId/media`](#get-apisessionssessionidmessageschatidmessageidmedia). Two rules bound the edges: the newest payload is always inlined even when it alone exceeds the budget (otherwise a single large photo would be permanently unreadable through this route), and a budget of `0` means "never inline" and grants no such allowance. The knob is validated at boot, `8MiB` would parse to 8 bytes, and is forwarded by both compose files. The MCP `MessageList` tool shares this path and the same budget. A row stored under `MESSAGE_INLINE_MEDIA=archive` arrives with the marker already in place, plus `archived: true`, its bytes live only in the chat-media archive, behind the same media route (see that route for the mode).**Errors:** `400` invalid filters or an unknown or mismatched cursor · `401` missing/invalid API key · `403` a key restricted to selected chats sent no `chatId`, or one outside its allowlistdiff --git a/src/engine/adapters/inbound-hold.spec.ts b/src/engine/adapters/inbound-hold.spec.tsindex 08b76604a..65e1d341a 100644--- a/src/engine/adapters/inbound-hold.spec.ts+++ b/src/engine/adapters/inbound-hold.spec.ts@@ -637,7 +637,7 @@ describe('Baileys inbound messages held for storage', () => {});await flush();- expect(h.rows).toEqual([{ ...real(), body: 'fixed' }]);+ expect(h.rows).toEqual([{ ...real(), body: 'fixed', metadata: { edited: true } }]);});});diff --git a/src/modules/session/message-edited-marker.spec.ts b/src/modules/session/message-edited-marker.spec.tsnew file mode 100644index 000000000..24e0c4102--- /dev/null+++ b/src/modules/session/message-edited-marker.spec.ts@@ -0,0 +1,103 @@+import { DataSource, type Repository } from 'typeorm';+import { Message, MessageDirection } from '../message/entities/message.entity';+import { MessageMutationProjector } from './message-mutation-projector';+import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';+import type { EventsGateway } from '../events/events.gateway';+import type { WebhookService } from '../webhook/webhook.service';+import type { LoggerService } from '../../common/services/logger.service';+import type { EditedMessage } from '../../engine/interfaces/whatsapp-engine.interface';++describe('persisted edited message marker', () => {+ let db: DataSource;+ let repository: Repository<Message>;+ let projector: MessageMutationProjector;+ let queue: KeyedMutationQueue;+ let emit: jest.Mock;++ beforeEach(async () => {+ db = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [Message], synchronize: true });+ await db.initialize();+ repository = db.getRepository(Message);+ queue = new KeyedMutationQueue();+ emit = jest.fn();+ projector = new MessageMutationProjector(+ repository,+ { emitMessageEdited: emit } as unknown as EventsGateway,+ { dispatch: jest.fn().mockResolvedValue(undefined) } as unknown as WebhookService,+ queue,+ { error: jest.fn(), warn: jest.fn() } as unknown as LoggerService,+ );+ });++ afterEach(async () => {+ await db.destroy();+ });++ const source = { kind: 'edit' as const, chatId: '[email protected]', fromMe: false };+ const edit = { messageId: 'WA_EDIT', chatId: source.chatId, fromMe: false, body: 'new' } as EditedMessage;+ const metadata = { reactions: { alice: '👍' }, media: { mimetype: 'image/jpeg', archived: true } };++ async function seed(type = 'text'): Promise<void> {+ await repository.save({+ sessionId: 's1',+ waMessageId: edit.messageId,+ chatId: source.chatId,+ from: source.chatId,+ to: 'me',+ direction: MessageDirection.INCOMING,+ body: 'old',+ type,+ metadata,+ });+ }++ async function drain(): Promise<void> {+ while (queue.size) await new Promise(resolve => setImmediate(resolve));+ }++ it('persists the inbound marker before notifying consumers, without losing other metadata', async () => {+ await seed();+ emit.mockImplementation(() => {+ // Inspect the storage at notification time, rather than assuming the queue wrote it first.+ const row = db.query('SELECT metadata FROM messages');+ return row.then((rows: Array<{ metadata: string }>) => {+ const storedMetadata = JSON.parse(rows[0].metadata) as Record<string, unknown>;+ expect(storedMetadata.edited).toBe(true);+ });+ });+ projector.applyMessageEditQueued('s1', edit);+ await drain();+ const stored = await repository.findOneByOrFail({ waMessageId: edit.messageId });+ expect(stored.body).toBe('new');+ expect(stored.metadata).toEqual({ ...metadata, edited: true });+ expect(emit).toHaveBeenCalledTimes(1);+ await emit.mock.results[0].value;+ });++ it('persists outbound edits as well', async () => {+ await seed();+ await repository.update({ waMessageId: edit.messageId }, { direction: MessageDirection.OUTGOING });+ await projector.recordOutboundMessageEdit('s1', edit.messageId, 'REST edit', { ...source, fromMe: true });+ const stored = await repository.findOneByOrFail({ waMessageId: edit.messageId });+ expect(stored.body).toBe('REST edit');+ expect(stored.metadata).toEqual({ ...metadata, edited: true });+ });++ it('does not restore or mark a revoked message', async () => {+ await seed('revoked');+ await repository.update({ waMessageId: edit.messageId }, { body: '', metadata: {} });+ projector.applyMessageEditQueued('s1', edit);+ await drain();+ const stored = await repository.findOneByOrFail({ waMessageId: edit.messageId });+ expect(stored.body).toBe('');+ expect(stored.metadata).toEqual({});+ });++ it('does not mark another chat when an edit names the wrong chat', async () => {+ await seed();+ projector.applyMessageEditQueued('s1', { ...edit, chatId: '[email protected]' });+ await drain();+ expect((await repository.findOneByOrFail({ waMessageId: edit.messageId })).metadata).toEqual(metadata);+ expect(emit).not.toHaveBeenCalled();+ });+});diff --git a/src/modules/session/message-mutation-projector.ts b/src/modules/session/message-mutation-projector.tsindex fb579e66a..fd3ccd914 100644--- a/src/modules/session/message-mutation-projector.ts+++ b/src/modules/session/message-mutation-projector.ts@@ -151,6 +151,7 @@ export class MessageMutationProjector {{ sessionId: id, waMessageId: message.messageId, type: Not('revoked') },{ body: message.body },);+ await this.markMessageEdited(id, message.messageId);} catch (err) {this.logger.error(`Failed to update edited message: ${message.messageId}`, String(err));}@@ -160,6 +161,14 @@ export class MessageMutationProjector {void this.webhookService.dispatch(id, 'message.edited', editedPayload);}+ /** Keep the marker alongside existing reactions, media and quote metadata. */+ private async markMessageEdited(sessionId: string, waMessageId: string): Promise<void> {+ await updateMessageMetadata(this.messageRepository, { sessionId, waMessageId }, metadata => ({+ ...metadata,+ edited: true,+ }));+ }+/*** Reflect an OUTBOUND edit (REST MessageService.editMessage) in the stored row, routed through the* same per-message mutation queue as the inbound edit/reaction paths so the two writers cannot@@ -187,6 +196,7 @@ export class MessageMutationProjector {return;}await this.messageRepository.update({ sessionId, waMessageId: messageId, type: Not('revoked') }, { body });+ await this.markMessageEdited(sessionId, messageId);} catch (err) {this.logger.warn(`Failed to update stored body of edited message ${messageId}`, { error: String(err) });} finally {