Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(engine): neutral MessageType instead of raw whatsapp-web.js type tokens (#265) (#270)

Yudhi Armyndharisb4495140b02c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7a8bc827d..01338a757 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Dashboard chat delivery ticks now update **live** over the websocket (the ack push was previously never emitted).
- Minor deprecated-surface deltas: the legacy webhook `ack` reports `3` (not `4`) for a "played" voice/video receipt,
and a play-after-read no longer emits a second `message.ack` (both map to `status: 'read'`).
+- **Message `type` is now an engine-neutral enum** (engine-pluggability decoupling, #265). Raw whatsapp-web.js
+ message-type tokens no longer leak past the engine adapter — incoming live/history messages, persisted rows, and the
+ `message.received`/`message.sent` webhooks now use a neutral `MessageType`
+ (`text`/`image`/`video`/`audio`/`voice`/`document`/`sticker`/`location`/`contact`/`revoked`/`unknown`), consistent with
+ outgoing sends. A non-whatsapp-web.js engine maps its own tokens at the adapter boundary.
+ - **Webhook contract change** (both `message.received` and `message.sent`): incoming `type` was previously raw — e.g.
+ `chat` → **`text`**, `ptt` → **`voice`**, `vcard` → **`contact`**. New consumers should expect the neutral enum.
+ - An idempotent startup backfill rewrites existing `messages.type` rows to the neutral vocabulary (runs in every DB
+ mode, including the zero-config SQLite default where data migrations don't), so historical chats render correctly
+ and message-type stats don't split the same kind across old/new tokens.
+ - Fixes a latent dashboard bug where incoming text (`chat`) was mis-styled as media and shown as `[chat]` in reply previews.
## [0.2.7] - 2026-06-16
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 10beaed03..837646c66 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -770,7 +770,6 @@ export function Chats() {
);
case 'audio':
case 'voice':
- case 'ptt':
return (
<div className="message-media-audio">
<audio src={mediaSrc} controls className="chat-audio-media" />
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 17dfa9547..1f34ae89a 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -886,7 +886,7 @@ GET /api/sessions/:sessionId/chats/:chatId/messages
"from": "[email protected]",
"body": "Hello!",
- "type": "chat",
+ "type": "text",
"waTimestamp": 1706868000,
"timestamp": "2025-02-02T10:00:00.000Z",
"fromMe": false,
@@ -1436,7 +1436,7 @@ flowchart TB
"from": "[email protected]",
"body": "Hello!",
- "type": "chat",
+ "type": "text",
"waTimestamp": 1706868000,
"timestamp": "2025-02-02T10:00:00.000Z",
"isGroup": false,
diff --git a/src/engine/adapters/message-mapper.spec.ts b/src/engine/adapters/message-mapper.spec.ts
index 4d145cd98..fb3baaa1c 100644
--- a/src/engine/adapters/message-mapper.spec.ts
+++ b/src/engine/adapters/message-mapper.spec.ts
@@ -1,4 +1,4 @@
-import { buildIncomingMessageBase, RawMessageFields } from './message-mapper';
+import { buildIncomingMessageBase, mapWwebjsMessageType, RawMessageFields } from './message-mapper';
describe('buildIncomingMessageBase', () => {
const base: RawMessageFields = {
@@ -11,10 +11,11 @@ describe('buildIncomingMessageBase', () => {
fromMe: false,
};
- it('maps the core fields and flags 1:1 chats as non-group', () => {
+ it('maps the core fields, neutralizes the type (chat -> text), and flags 1:1 chats as non-group', () => {
const r = buildIncomingMessageBase(base);
expect(r.id).toBe('MSG1');
expect(r.chatId).toBe('[email protected]');
+ expect(r.type).toBe('text'); // wwebjs 'chat' is neutralized to 'text'
expect(r.isGroup).toBe(false);
expect(r.author).toBeUndefined();
expect(r.contact).toBeUndefined();
@@ -50,3 +51,22 @@ describe('buildIncomingMessageBase', () => {
expect(r.isGroup).toBe(true);
});
});
+
+describe('mapWwebjsMessageType (engine type-token -> neutral MessageType boundary, #265)', () => {
+ it.each([
+ ['chat', 'text'],
+ ['ptt', 'voice'],
+ ['image', 'image'],
+ ['video', 'video'],
+ ['audio', 'audio'],
+ ['document', 'document'],
+ ['sticker', 'sticker'],
+ ['location', 'location'],
+ ['vcard', 'contact'],
+ ['multi_vcard', 'contact'],
+ ['revoked', 'revoked'],
+ ['e2e_notification', 'unknown'], // any unmapped wwebjs type
+ ])('maps wwebjs type %s -> %s', (raw, expected) => {
+ expect(mapWwebjsMessageType(raw)).toBe(expected);
+ });
+});
diff --git a/src/engine/adapters/message-mapper.ts b/src/engine/adapters/message-mapper.ts
index dd4fb7c21..39ea0cd46 100644
--- a/src/engine/adapters/message-mapper.ts
+++ b/src/engine/adapters/message-mapper.ts
@@ -1,4 +1,38 @@
-import { IncomingMessage } from '../interfaces/whatsapp-engine.interface';
+import { IncomingMessage, MessageType } from '../interfaces/whatsapp-engine.interface';
+
+/**
+ * Map a whatsapp-web.js `MessageTypes` token to the engine-neutral {@link MessageType}, so no
+ * consumer outside the adapter sees wwebjs-specific type strings. Notably `chat` -> `text` (aligning
+ * incoming with the neutral types outgoing sends already use) and `ptt` -> `voice`. Anything not
+ * mapped becomes `unknown`.
+ */
+export function mapWwebjsMessageType(raw: string): MessageType {
+ switch (raw) {
+ case 'chat':
+ return 'text';
+ case 'image':
+ return 'image';
+ case 'video':
+ return 'video';
+ case 'audio':
+ return 'audio';
+ case 'ptt':
+ return 'voice';
+ case 'document':
+ return 'document';
+ case 'sticker':
+ return 'sticker';
+ case 'location':
+ return 'location';
+ case 'vcard':
+ case 'multi_vcard':
+ return 'contact';
+ case 'revoked':
+ return 'revoked';
+ default:
+ return 'unknown';
+ }
+}
/**
* The subset of whatsapp-web.js `Message` fields we read synchronously to build
@@ -34,7 +68,7 @@ export function buildIncomingMessageBase(msg: RawMessageFields): IncomingMessage
to: msg.to,
chatId,
body: msg.body,
- type: msg.type,
+ type: mapWwebjsMessageType(msg.type),
timestamp: msg.timestamp,
fromMe: msg.fromMe,
isGroup: chatId.endsWith('@g.us'),
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index ae0c3bb66..d595cbeef 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -22,13 +22,32 @@ export interface MediaInput {
caption?: string;
}
+/**
+ * Engine-neutral message type. Each adapter maps its library's native message-type tokens
+ * (e.g. whatsapp-web.js `chat`/`ptt`/`vcard`) to this vocabulary at the adapter boundary,
+ * so no consumer outside the adapter sees engine-specific type strings. `unknown` covers any
+ * type the active engine reports that doesn't map to a first-class kind.
+ */
+export type MessageType =
+ | 'text'
+ | 'image'
+ | 'video'
+ | 'audio'
+ | 'voice'
+ | 'document'
+ | 'sticker'
+ | 'location'
+ | 'contact'
+ | 'revoked'
+ | 'unknown';
+
export interface IncomingMessage {
id: string;
from: string;
to: string;
chatId: string;
body: string;
- type: string;
+ type: MessageType;
timestamp: number;
fromMe: boolean;
isGroup: boolean;
diff --git a/src/modules/message/message-type-backfill.service.spec.ts b/src/modules/message/message-type-backfill.service.spec.ts
new file mode 100644
index 000000000..629d4f41a
--- /dev/null
+++ b/src/modules/message/message-type-backfill.service.spec.ts
@@ -0,0 +1,32 @@
+import { In, Repository } from 'typeorm';
+import { MessageTypeBackfillService } from './message-type-backfill.service';
+import { Message } from './entities/message.entity';
+
+describe('MessageTypeBackfillService', () => {
+ const makeService = (update: jest.Mock) => {
+ const repo = { update } as unknown as Repository<Message>;
+ return new MessageTypeBackfillService(repo);
+ };
+
+ it('rewrites each legacy wwebjs token to the neutral MessageType on bootstrap', async () => {
+ const update = jest.fn().mockResolvedValue({ affected: 1 });
+ await makeService(update).onApplicationBootstrap();
+
+ expect(update).toHaveBeenCalledTimes(3);
+ expect(update).toHaveBeenCalledWith({ type: 'chat' }, { type: 'text' });
+ expect(update).toHaveBeenCalledWith({ type: 'ptt' }, { type: 'voice' });
+ // vcard + multi_vcard collapse to contact via an IN clause
+ expect(update).toHaveBeenCalledWith({ type: In(['vcard', 'multi_vcard']) }, { type: 'contact' });
+ });
+
+ it('is a no-op-safe write (idempotent): affected:0 on already-neutral rows does not throw', async () => {
+ const update = jest.fn().mockResolvedValue({ affected: 0 });
+ await expect(makeService(update).onApplicationBootstrap()).resolves.toBeUndefined();
+ expect(update).toHaveBeenCalledTimes(3);
+ });
+
+ it('does not crash boot if the backfill query fails', async () => {
+ const update = jest.fn().mockRejectedValue(new Error('db down'));
+ await expect(makeService(update).onApplicationBootstrap()).resolves.toBeUndefined();
+ });
+});
diff --git a/src/modules/message/message-type-backfill.service.ts b/src/modules/message/message-type-backfill.service.ts
new file mode 100644
index 000000000..034396b12
--- /dev/null
+++ b/src/modules/message/message-type-backfill.service.ts
@@ -0,0 +1,63 @@
+import { Injectable, OnApplicationBootstrap } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+import { In, Repository } from 'typeorm';
+import { Message } from './entities/message.entity';
+import { createLogger } from '../../common/services/logger.service';
+
+/**
+ * One-time, idempotent backfill of `messages.type` to the engine-neutral vocabulary (#265).
+ *
+ * Older incoming rows were persisted with raw whatsapp-web.js tokens (`chat`/`ptt`/`vcard`); the
+ * engine now emits neutral types (`text`/`voice`/`contact`) at the adapter boundary, and the
+ * dashboard chat view + message stats read these persisted rows. Without the backfill, old rows
+ * render wrong (text as a `[chat]` media bubble, voice notes as document links) and stats split the
+ * same kind across old/new tokens.
+ *
+ * This runs on startup in EVERY DB mode. A TypeORM data migration would NOT suffice: the zero-config
+ * SQLite default uses `synchronize: true`, under which `migrationsRun` is false, so migrations never
+ * run there. The mapping is forward-only and collision-free (the neutral targets were never valid
+ * raw tokens, and passthrough kinds already match), so re-running on already-converted rows is a
+ * no-op — safe to execute on every boot.
+ */
+@Injectable()
+export class MessageTypeBackfillService implements OnApplicationBootstrap {
+ private readonly logger = createLogger('MessageTypeBackfill');
+
+ constructor(
+ @InjectRepository(Message, 'data')
+ private readonly messageRepository: Repository<Message>,
+ ) {}
+
+ async onApplicationBootstrap(): Promise<void> {
+ // [legacy wwebjs token(s)] -> neutral MessageType. Kept in sync with mapWwebjsMessageType.
+ const conversions: Array<{ from: string[]; to: string }> = [
+ { from: ['chat'], to: 'text' },
+ { from: ['ptt'], to: 'voice' },
+ { from: ['vcard', 'multi_vcard'], to: 'contact' },
+ ];
+
+ let total = 0;
+ try {
+ for (const { from, to } of conversions) {
+ const result = await this.messageRepository.update(
+ { type: from.length === 1 ? from[0] : In(from) },
+ { type: to },
+ );
+ total += result.affected ?? 0;
+ }
+ if (total > 0) {
+ this.logger.log(`Backfilled ${total} legacy message type(s) to the neutral vocabulary`, {
+ action: 'message_type_backfill',
+ });
+ }
+ } catch (error) {
+ // Non-fatal: new rows are already neutral; only historical rows are affected. Surface it so it
+ // can be re-run (e.g. via a restart) rather than crashing boot.
+ this.logger.error(
+ 'Failed to backfill legacy message types',
+ error instanceof Error ? error.stack : String(error),
+ { action: 'message_type_backfill_failed' },
+ );
+ }
+ }
+}
diff --git a/src/modules/message/message.module.ts b/src/modules/message/message.module.ts
index 522001e7b..724ef35c2 100644
--- a/src/modules/message/message.module.ts
+++ b/src/modules/message/message.module.ts
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { MessageService } from './message.service';
import { BulkMessageService } from './bulk-message.service';
+import { MessageTypeBackfillService } from './message-type-backfill.service';
import { MessageController } from './message.controller';
import { SessionModule } from '../session/session.module';
import { TemplateModule } from '../template/template.module';
@@ -11,7 +12,7 @@ import { MessageBatch } from './entities/message-batch.entity';
@Module({
imports: [TypeOrmModule.forFeature([Message, MessageBatch], 'data'), SessionModule, TemplateModule],
controllers: [MessageController],
- providers: [MessageService, BulkMessageService],
+ providers: [MessageService, BulkMessageService, MessageTypeBackfillService],
exports: [MessageService, BulkMessageService],
})
export class MessageModule {}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 346b3dcfe..d6b740f96 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -412,7 +412,7 @@ describe('SessionService', () => {
chatId: '[email protected]',
body: 'hello',
- type: 'chat',
+ type: 'text',
timestamp: 1706868000,
fromMe: false,
isGroup: false,