Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(chats): give group messages a stable sender identity for attribution
Yudhi Armyndharisa7caf9ac93a5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2012b0f84..6be0e962f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- **Group messages now carry a stable sender identity, so same-named participants no longer blur+ together.** Group messages persist the participant JID (new `author` column on `messages`) next+ to the sender's display name, and the dashboard keys attribution runs and sender colors on that+ identity instead of the name — two participants who share a pushName now get separate runs in+ distinct colors instead of collapsing into one misattributed thread. Live, history-backfilled,+ and websocket-delivered messages all carry it; legacy rows fall back to name-keying.+## [0.10.9] - 2026-07-24### Addeddiff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 53f68e618..fbe827f78 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -43,6 +43,7 @@ import {mergeDeliveryStatus,mergeOrAppend,findRevokedIndex,+ senderKey,type ChatMessageView,} from '../utils/chatMessages';import { useWebSocket } from '../hooks/useWebSocket';@@ -566,6 +567,7 @@ export function Chats() {// For a group post `from` is the group JID, so the sender's name is carried on `contact`.// Persisted rows keep the same value in `chatName`; normalize both to one field for the thread.chatName: newMsg.contact?.pushName ?? newMsg.contact?.name,+ author: newMsg.author,from: newMsg.from,to: newMsg.to,body: newMsg.body,@@ -1536,7 +1538,9 @@ export function Chats() {activeChat?.isGroup &&!isMe &&msg.chatName &&- (!prev || prev.direction === 'outgoing' || prev.chatName !== msg.chatName),+ // Key the run on the stable sender id (participant JID), not the display+ // name — two participants who share a pushName must still start a new run.+ (!prev || prev.direction === 'outgoing' || senderKey(prev) !== senderKey(msg)),);const isMediaMessage = msg.type !== 'text';@@ -1654,8 +1658,11 @@ export function Chats() {} ${isRevoked ? 'revoked-type' : ''}`}>{/* Group sender label (WhatsApp-style: coloured name atop the bubble) */}+ {/* Group sender label (WhatsApp-style: coloured name atop the bubble).+ Colour keys on the stable sender id, so same-named participants+ still get distinct colours; the label shows the human name. */}{showSender && (- <div className="message-sender" style={{ color: senderColor(msg.chatName!) }}>+ <div className="message-sender" style={{ color: senderColor(senderKey(msg)!) }}>{msg.chatName}</div>)}diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex d1b954d6d..d403c82a7 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -184,6 +184,12 @@ export interface ChatMessage {* on legacy rows or when the engine could not resolve a name.*/chatName?: string;+ /**+ * Stable sender identity for a group message: the participant JID who actually posted (`from` is+ * the group JID). Present on live/engine payloads and on rows persisted after the column was+ * added; absent on 1:1 messages, outgoing echoes, and legacy rows.+ */+ author?: string;from: string;to: string;body: string;diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.tsindex 8406fc45b..8d5bcf633 100644--- a/dashboard/src/utils/chatMessages.test.ts+++ b/dashboard/src/utils/chatMessages.test.ts@@ -95,6 +95,7 @@ import {removeMessageById,findRevokedIndex,applyMessageEdit,+ senderKey,type ChatMessageView,} from './chatMessages.ts';@@ -282,3 +283,39 @@ test('applyMessageEdit is a referential no-op for an empty or unknown target id'assert.equal(applyMessageEdit(before, { messageId: '', body: 'new' }), before);assert.equal(applyMessageEdit(before, { messageId: 'missing', body: 'new' }), before);});++test('mapEngineHistoryMessage: carries the group participant JID as author', () => {+ const m = mapEngineHistoryMessage(hist({ author: '[email protected]' }));+ assert.equal(m.author, '[email protected]');+});++test('mergeChatMessages: salvages author from the engine copy when the DB row predates the column', () => {+ // A legacy DB row (no stable sender id) merged over an engine-history copy that has one must not+ // lose it — that id is what keeps same-named participants in separate attribution runs.+ const history = [mapEngineHistoryMessage(hist({ id: 'WA_S1', author: '[email protected]' }))];+ const rows = [db({ waMessageId: 'WA_S1', author: undefined })];+ const merged = mergeChatMessages(rows, history);+ assert.equal(merged.length, 1);+ assert.equal(merged[0].author, '[email protected]');+ // …while the rest of the winning DB row (authoritative status) is untouched.+ assert.equal(merged[0].status, 'delivered');+});++test('mergeChatMessages: a DB-persisted author wins over the engine copy', () => {+ const history = [mapEngineHistoryMessage(hist({ id: 'WA_S2', author: '[email protected]' }))];+ const rows = [db({ waMessageId: 'WA_S2', author: '[email protected]' })];+ assert.equal(mergeChatMessages(rows, history)[0].author, '[email protected]');+});++test('mergeOrAppend: an author-less echo keeps the cached author', () => {+ const list = [msg({ id: 'WA_E1', waMessageId: 'WA_E1', author: '[email protected]' })];+ const echo = msg({ id: 'WA_E1', waMessageId: 'WA_E1', author: undefined, body: 'echo' });+ const out = mergeOrAppend(list, echo);+ assert.equal(out[0].author, '[email protected]');+});++test('senderKey prefers the participant JID and falls back to the display name', () => {+ assert.equal(senderKey({ author: '[email protected]', chatName: 'Alice' }), '[email protected]');+ assert.equal(senderKey({ chatName: 'Alice' }), 'Alice');+ assert.equal(senderKey({}), undefined);+});diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.tsindex 24b01788b..06d485066 100644--- a/dashboard/src/utils/chatMessages.ts+++ b/dashboard/src/utils/chatMessages.ts@@ -16,6 +16,7 @@ export function mapEngineHistoryMessage(h: EngineHistoryMessage): ChatMessage {waMessageId: h.id,chatId: h.chatId,chatName: h.contact?.pushName ?? h.contact?.name,+ author: h.author,from: h.from,to: h.to,body: h.body ?? '',@@ -42,10 +43,25 @@ const msgTime = (m: ChatMessage): number =>export function mergeChatMessages(db: ChatMessage[], history: ChatMessage[]): ChatMessage[] {const byId = new Map<string, ChatMessage>();for (const m of history) byId.set(msgKey(m), m);- for (const m of db) byId.set(msgKey(m), m); // DB overwrites the engine copy (authoritative status)+ for (const m of db) {+ const key = msgKey(m);+ const hist = byId.get(key);+ // The DB copy wins (authoritative status) — but a legacy row has no stable sender id, so+ // salvage the engine-history copy's author or two same-named participants collapse into one+ // attribution run in the chat view.+ byId.set(key, hist?.author && !m.author ? { ...m, author: hist.author } : m);+ }return [...byId.values()].sort((a, b) => msgTime(a) - msgTime(b) || a.createdAt.localeCompare(b.createdAt));}+/**+ * Stable identity of a group message's sender, for attribution runs and sender colors: the+ * participant JID (`author`) when present, falling back to the display name on legacy rows. Keying+ * on this — not the name alone — keeps two participants who share a pushName from collapsing into+ * one run with one color.+ */+export const senderKey = (m: Pick<ChatMessage, 'author' | 'chatName'>): string | undefined => m.author ?? m.chatName;+// ChatMessageView extends ChatMessage with the view-only fields the chat page renders.// Lifted from Chats.tsx so hooks/utils can share the same shape.type MessageMedia = { mimetype: string; filename?: string; data?: string; omitted?: boolean; sizeBytes?: number };@@ -125,6 +141,8 @@ export function mergeOrAppend(list: ChatMessageView[], incoming: ChatMessageViewconst next = list.slice();next[idx] = {...incoming,+ // An echo that lacks the stable sender id must not erase the one already cached.+ author: incoming.author ?? existing.author,status: mergeDeliveryStatus(existing.status, incoming.status) ?? incoming.status,metadata: mergeMessageMetadata(existing.metadata, incoming.metadata),};diff --git a/src/database/migrations/1784908800000-AddMessageAuthor.ts b/src/database/migrations/1784908800000-AddMessageAuthor.tsnew file mode 100644index 000000000..a15990b68--- /dev/null+++ b/src/database/migrations/1784908800000-AddMessageAuthor.ts@@ -0,0 +1,29 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Adds `author` column to the `messages` table. For a group message this stores the participant+ * JID who actually posted (the row's `from` is the group JID), giving the chat view a stable+ * sender identity — two participants who share a pushName no longer collapse into one attribution+ * run. Null for one-to-one messages, outgoing echoes, and legacy rows.+ *+ * Hand-authored because `synchronize` is off for the `data` connection on PostgreSQL (and optional+ * on SQLite via DATABASE_SYNCHRONIZE=false). Idempotent: checks for column existence first.+ */+export class AddMessageAuthor1784908800000 implements MigrationInterface {+ name = 'AddMessageAuthor1784908800000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ const table = await queryRunner.getTable('messages');+ const col = table?.findColumnByName('author');+ if (col) return; // already added by synchronize or a previous run++ await queryRunner.query(`ALTER TABLE "messages" ADD COLUMN "author" varchar NULL`);+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ const table = await queryRunner.getTable('messages');+ const col = table?.findColumnByName('author');+ if (!col) return;+ await queryRunner.query(`ALTER TABLE "messages" DROP COLUMN "author"`);+ }+}diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.tsindex df3425b42..dbddb3943 100644--- a/src/modules/message/entities/message.entity.ts+++ b/src/modules/message/entities/message.entity.ts@@ -56,6 +56,14 @@ export class Message {@Column({ nullable: true })chatName?: string;+ /**+ * Stable sender identity for a group message: the participant JID who actually posted (`from` is+ * the group JID). Lets the chat view tell two same-named participants apart. Null on 1:1+ * messages, outgoing echoes, and legacy rows.+ */+ @Column({ nullable: true })+ author?: string;+@Column()from: string;diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 1272c10ee..965dfa2e9 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1833,6 +1833,35 @@ describe('SessionService', () => {expect(row.metadata).toEqual({ media: marker });});+ it('persists the group participant as author (the stable sender id attribution keys on)', async () => {+ const callbacks = await startAndCaptureCallbacks();+ // Pass the message through the hook chain untouched (the default mock replaces data with {}).+ (hookManager.execute as jest.Mock).mockImplementation((_e: string, data: unknown) =>+ Promise.resolve({ continue: true, data }),+ );++ callbacks.onMessage!(+ makeMessage({+ id: 'wa-grp-1',+ from: '[email protected]',+ to: '[email protected]',+ chatId: '[email protected]',+ fromMe: false,+ isGroup: true,+ kind: 'group',+ author: '[email protected]',+ contact: { id: '[email protected]', pushName: 'Alice' },+ }),+ );+ await flush();++ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const row = (messageRepository.create as jest.Mock).mock.calls[0][0] as Partial<Message>;+ expect(row.author).toBe('[email protected]');+ expect(row.from).toBe('[email protected]');+ expect(row.chatName).toBe('Alice');+ });+it('scopes the ack status UPDATE by sessionId, not just waMessageId', async () => {const callbacks = await startAndCaptureCallbacks();expect(typeof callbacks.onMessageAck).toBe('function');diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex bd34e2152..aa97853a1 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -803,6 +803,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatsessionId: id,waMessageId: m.id,chatId: m.chatId,+ author: m.author,from: m.from,to: m.to,body: m.body,@@ -1049,6 +1050,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatwaMessageId: incoming.id || undefined,chatId: incoming.chatId,chatName,+ // Group poster (participant JID) — `from` is the group JID, so this is the stable+ // sender identity the chat view keys attribution runs/colors on. Undefined for 1:1.+ author: incoming.author,from: incoming.from,to: incoming.to,body: incoming.body,