Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(chats): expose last-message types

Yudhi Armyndharis139ce4dbfe3d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6fb92e23c..e56f82851 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- Expose optional last-message types in chat lists and SDKs.
- Add bounded webhook failure redrive with optional payload retention.
- Expose caller-supplied send idempotency keys in all five SDKs.
- Add optional 24-hour idempotency keys to twelve single-recipient send routes.
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 8566a2ece..e2a2331a7 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -562,7 +562,11 @@ export function Chats() {
});
}
if (revokedLastMessage) {
- setChats(previous => previous.map(chat => (chat.id === event.chatId ? { ...chat, lastMessage: '' } : chat)));
+ setChats(previous =>
+ previous.map(chat =>
+ chat.id === event.chatId ? { ...chat, lastMessage: '', lastMessageType: 'revoked' } : chat,
+ ),
+ );
} else if (!matchedCachedMessage) {
// No cached thread proves whether the deleted message was the chat's newest; refresh the
// summaries, as an edit does.
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 0de77199a..1322044e4 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -255,6 +255,7 @@ export interface Chat {
unreadCount: number;
timestamp: number;
lastMessage?: string;
+ lastMessageType?: MessageType;
archived: boolean;
pinned: boolean;
muted: boolean;
diff --git a/dashboard/src/utils/chatList.test.ts b/dashboard/src/utils/chatList.test.ts
index ee4adf718..ad9763632 100644
--- a/dashboard/src/utils/chatList.test.ts
+++ b/dashboard/src/utils/chatList.test.ts
@@ -26,6 +26,7 @@ test('an arriving message moves its chat to the top and refreshes the snippet',
);
assert.equal(chats[0].lastMessage, 'hi');
+ assert.equal(chats[0].lastMessageType, 'text');
assert.equal(chats[0].timestamp, 200);
assert.deepEqual(
before.map(c => c.id),
@@ -113,7 +114,7 @@ test('an INCOMING message from an unknown @lid chat still asks for a refetch', (
});
test('promoteChatWithSnippet moves the sent-into chat to the top', () => {
- const before = [chat('[email protected]'), chat('[email protected]')];
+ const before = [chat('[email protected]'), chat('[email protected]', { lastMessageType: 'voice' })];
const after = promoteChatWithSnippet(before, '[email protected]', '[image]', 999);
@@ -122,6 +123,8 @@ test('promoteChatWithSnippet moves the sent-into chat to the top', () => {
);
assert.equal(after[0].lastMessage, '[image]');
+ assert.equal(after[0].lastMessageType, undefined);
+ assert.equal(before[1].lastMessageType, 'voice');
assert.equal(after[0].timestamp, 999);
assert.deepEqual(
before.map(c => c.id),
diff --git a/dashboard/src/utils/chatList.ts b/dashboard/src/utils/chatList.ts
index a1268cc81..d09059699 100644
--- a/dashboard/src/utils/chatList.ts
+++ b/dashboard/src/utils/chatList.ts
@@ -13,6 +13,7 @@
export interface ChatListEntry {
id: string;
lastMessage?: string;
+ lastMessageType?: string;
timestamp?: number;
unreadCount?: number;
}
@@ -63,6 +64,7 @@ export function applyIncomingToChatList<T extends ChatListEntry>(
const updated = [...chats];
const target = { ...updated[index] };
target.lastMessage = msg.type === 'location' ? opts.locationLabel : msg.body;
+ target.lastMessageType = msg.type;
target.timestamp = msg.timestamp;
if (!msg.fromMe && opts.activeChatId !== target.id) {
// A chat marked unread carries -1; the first message into it counts as 1, not 0.
@@ -86,7 +88,7 @@ export function promoteChatWithSnippet<T extends ChatListEntry>(
const index = chats.findIndex(c => c.id === chatId);
if (index === -1) return chats;
const updated = [...chats];
- const target = { ...updated[index], lastMessage: snippet, timestamp };
+ const target = { ...updated[index], lastMessage: snippet, lastMessageType: undefined, timestamp };
updated.splice(index, 1);
updated.unshift(target);
return updated;
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index d502a70f0..69b6dc775 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -497,6 +497,7 @@ Get active chats for a session, most-recent first (paginated).
"unreadCount": 2,
"timestamp": 1719306115,
"lastMessage": "See you tomorrow",
+ "lastMessageType": "text",
"archived": false,
"pinned": false,
"muted": false
@@ -504,6 +505,8 @@ Get active chats for a session, most-recent first (paginated).
]
```
+`lastMessageType` uses the same engine-neutral types as messages, such as `text`, `image`, `voice`, and `document`. It identifies media even when `lastMessage` has no caption. The field is omitted when the engine has no last message available; on Baileys it becomes available after history sync or a new message.
+
`archived`, `pinned` and `muted` are the read side of the `chats/archive`, `chats/pin` and
`chats/mute` endpoints. `muted` is the verdict; `muteExpiration`, present only when `muted` is true,
is the instant the mute ends in epoch milliseconds (`0` = indefinite), the same unit as
diff --git a/openapi.json b/openapi.json
index 63e1f59a7..f9595044a 100644
--- a/openapi.json
+++ b/openapi.json
@@ -18636,6 +18636,29 @@
"type": "string",
"example": "hi"
},
+ "lastMessageType": {
+ "type": "string",
+ "enum": [
+ "text",
+ "image",
+ "video",
+ "audio",
+ "voice",
+ "document",
+ "sticker",
+ "location",
+ "contact",
+ "poll",
+ "call",
+ "revoked",
+ "order",
+ "product",
+ "masked",
+ "unknown"
+ ],
+ "description": "Engine-neutral type of the last message, when available.",
+ "example": "image"
+ },
"archived": {
"type": "boolean",
"description": "Archived state, as set via POST /sessions/{sessionId}/chats/archive.",
diff --git a/sdk/go/chat_history_decode_test.go b/sdk/go/chat_history_decode_test.go
index 2007abdc8..7e7754453 100644
--- a/sdk/go/chat_history_decode_test.go
+++ b/sdk/go/chat_history_decode_test.go
@@ -54,3 +54,24 @@ func TestChatHistoryMessageLeavesAbsentFieldsEmpty(t *testing.T) {
t.Errorf("absent scalars should stay zero: ephemeral=%d bg=%q", m.EphemeralDuration, m.BackgroundColor)
}
}
+
+func TestChatSummaryDecodesOptionalLastMessageType(t *testing.T) {
+ var chats []ChatSummary
+ if err := json.Unmarshal([]byte(`[{"id":"[email protected]","lastMessageType":"image"},{"id":"[email protected]"}]`), &chats); err != nil {
+ t.Fatal(err)
+ }
+ if chats[0].LastMessageType != MsgImage || chats[1].LastMessageType != "" {
+ t.Fatalf("unexpected types: %+v", chats)
+ }
+ wire, err := json.Marshal(chats[1])
+ if err != nil {
+ t.Fatal(err)
+ }
+ var empty map[string]interface{}
+ if err := json.Unmarshal(wire, &empty); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := empty["lastMessageType"]; ok {
+ t.Fatal("absent type must stay omitted")
+ }
+}
diff --git a/sdk/go/types_chat.go b/sdk/go/types_chat.go
index 9ede2bdad..35801fe51 100644
--- a/sdk/go/types_chat.go
+++ b/sdk/go/types_chat.go
@@ -4,15 +4,16 @@ import "net/url"
// ChatSummary is a chat-list entry.
type ChatSummary struct {
- ID string `json:"id"`
- Name string `json:"name"`
- IsGroup bool `json:"isGroup"`
- UnreadCount int `json:"unreadCount"`
- LastMessage string `json:"lastMessage,omitempty"`
- Timestamp int64 `json:"timestamp"`
- Kind ChatKind `json:"kind"`
- Archived bool `json:"archived"`
- Pinned bool `json:"pinned"`
+ ID string `json:"id"`
+ Name string `json:"name"`
+ IsGroup bool `json:"isGroup"`
+ UnreadCount int `json:"unreadCount"`
+ LastMessage string `json:"lastMessage,omitempty"`
+ LastMessageType MessageType `json:"lastMessageType,omitempty"`
+ Timestamp int64 `json:"timestamp"`
+ Kind ChatKind `json:"kind"`
+ Archived bool `json:"archived"`
+ Pinned bool `json:"pinned"`
// Muted reports whether the chat is muted right now, not the expiry behind it.
Muted bool `json:"muted"`
// MuteExpiration is the epoch milliseconds the mute ends, present only when muted; 0 means
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatSummary.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatSummary.java
index 9c9493d11..9900654c9 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatSummary.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatSummary.java
@@ -20,4 +20,15 @@ public record ChatSummary(
/** Whether the chat is muted right now, not the expiry behind it. */
Boolean muted,
/** Epoch milliseconds the mute ends, null unless muted; 0 means indefinitely. */
- Long muteExpiration) {}
+ Long muteExpiration,
+ MessageType lastMessageType) {
+
+ /** Construct a chat summary without last-message type metadata. */
+ public ChatSummary(
+ String id, String name, Boolean isGroup, Integer unreadCount, String lastMessage,
+ Long timestamp, ChatKind kind, Boolean archived, Boolean pinned, Boolean muted,
+ Long muteExpiration) {
+ this(id, name, isGroup, unreadCount, lastMessage, timestamp, kind, archived, pinned,
+ muted, muteExpiration, null);
+ }
+}
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChatsResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChatsResourceTest.java
index 03f6091a8..3789259b0 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChatsResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChatsResourceTest.java
@@ -1,12 +1,15 @@
package com.rmyndharis.openwa.resources;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.rmyndharis.openwa.ClientConfig;
import com.rmyndharis.openwa.OpenWAClient;
import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.ChatState;
+import com.rmyndharis.openwa.model.ChatSummary;
+import com.rmyndharis.openwa.model.MessageType;
import com.rmyndharis.openwa.model.ArchiveChatRequest;
import com.rmyndharis.openwa.model.DeleteChatRequest;
import com.rmyndharis.openwa.model.MuteChatRequest;
@@ -31,6 +34,16 @@ class ChatsResourceTest {
assertEquals(HttpMethod.GET, tx.lastRequest().method());
}
+ @Test
+ void listDecodesOptionalLastMessageType() {
+ tx.respond(200, "[{\"id\":\"[email protected]\",\"lastMessageType\":\"image\"},{\"id\":\"[email protected]\"}]");
+ var chats = client.chats.list("s");
+ assertEquals(MessageType.IMAGE, chats.get(0).lastMessageType());
+ assertNull(chats.get(1).lastMessageType());
+ var legacy = new ChatSummary("id", "name", false, 0, "hi", 1L, null, false, false, false, null);
+ assertNull(legacy.lastMessageType());
+ }
+
@Test
void listEncodesSessionId() {
tx.respond(200, "[]");
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 0ea6790cb..bd3047b0f 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -1075,6 +1075,7 @@ export interface ChatSummary {
unreadCount: number;
/** Preview text of the last message (the server returns a plain string, not an object). */
lastMessage?: string;
+ lastMessageType?: MessageType;
/** Unix seconds of the last activity. */
timestamp: number;
kind: ChatKind;
diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.ts
index 9b0e8f146..1d595ed77 100644
--- a/sdk/javascript/test/resources.test.ts
+++ b/sdk/javascript/test/resources.test.ts
@@ -383,6 +383,17 @@ describe('ChatsResource — exact paths', () => {
});
});
+describe('ChatsResource last-message metadata', () => {
+ it('keeps media types and omitted metadata from the server response', async () => {
+ const t = new MockTransport().on('GET', /\/chats$/, {
+ body: [{ id: '[email protected]', lastMessageType: 'image' }, { id: '[email protected]' }],
+ });
+ const chats = await client(t).chats.list('s');
+ expect(chats[0].lastMessageType).toBe('image');
+ expect(chats[1].lastMessageType).toBeUndefined();
+ });
+});
+
describe('ChatsResource.clearMessages', () => {
it('DELETEs the chat messages sub-resource', async () => {
const t = new MockTransport().on('DELETE', /\/chats\/.+\/messages$/, { body: { success: true } });
diff --git a/sdk/php/src/Resources/ChatsResource.php b/sdk/php/src/Resources/ChatsResource.php
index 70cd50a9c..55cf2e967 100644
--- a/sdk/php/src/Resources/ChatsResource.php
+++ b/sdk/php/src/Resources/ChatsResource.php
@@ -22,6 +22,8 @@ class ChatsResource
}
/**
+ * Entries include lastMessageType when the engine knows the last message kind.
+ *
* @param array<string,mixed> $query
* @return array<int,array<string,mixed>>
*/
diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.php
index 3201a6f49..383221072 100644
--- a/sdk/php/tests/ResourcesTest.php
+++ b/sdk/php/tests/ResourcesTest.php
@@ -305,6 +305,15 @@ class ResourcesTest extends TestCase
// ── Chats & Health ────────────────────────────────────────────────
+ public function testChatsPreserveOptionalLastMessageType(): void
+ {
+ $backend = new MockBackend();
+ $backend->on(200, [['id' => '[email protected]', 'lastMessageType' => 'image'], ['id' => '[email protected]']]);
+ $chats = $backend->makeClient()->chats->list('s');
+ $this->assertSame('image', $chats[0]['lastMessageType']);
+ $this->assertArrayNotHasKey('lastMessageType', $chats[1]);
+ }
+
public function testChats(): void
{
$backend = new MockBackend();
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index 199283d43..515e784dc 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -1039,6 +1039,7 @@ class ChatSummary(TypedDict):
unreadCount: int
# Server returns a plain preview string, not a message object.
lastMessage: NotRequired[str]
+ lastMessageType: NotRequired[MessageType]
timestamp: int
kind: ChatKind
archived: bool
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index ac4e22dfe..eb7fdff6a 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -897,6 +897,14 @@ class TestStatus:
class TestChatsAndHealth:
+ def test_chats_preserve_optional_last_message_type(self):
+ backend = MockBackend().on("GET", "/chats", body=[
+ {"id": "[email protected]", "lastMessageType": "image"}, {"id": "[email protected]"},
+ ])
+ chats = make_client(backend).chats.list("s")
+ assert chats[0]["lastMessageType"] == "image"
+ assert "lastMessageType" not in chats[1]
+
def test_chats(self):
backend = MockBackend()
backend.on("GET", "/chats", body=[])
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index 8a54e9a9f..49d803835 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -9,6 +9,7 @@ import {
PresenceState,
CallOutcome,
IncomingMessage,
+ MessageType,
ReactionEvent,
RevokedMessage,
} from '../interfaces/whatsapp-engine.interface';
@@ -173,9 +174,9 @@ export interface BaileysEventsHost {
/** Learn any lid->pn pair a message key carries (also writes through to the persistent table). */
recordKeyLidMappings(key: Pick<WAMessageKey, 'remoteJid' | 'remoteJidAlt' | 'participant' | 'participantAlt'>): void;
/** Seed the chat's last-message preview + sort time from an inbound message. */
- recordMessage(msg: WAMessage): void;
+ recordMessage(msg: WAMessage, type?: MessageType): void;
/** Apply a message edit to the stored body. */
- recordMessageEdit(chatId: string, messageId: string, text: string): void;
+ recordMessageEdit(chatId: string, messageId: string, text: string, type?: MessageType): void;
/** Persist an inbound message to the store; undefined when no store is configured. */
putStoredMessage(msg: WAMessage): Promise<void> | undefined;
/** Rewrite a stored message in place (see BaileysMessageStore.update); undefined without a store. */
@@ -446,7 +447,7 @@ export class BaileysEvents {
body: '',
timestamp: toUnixSeconds(msg.messageTimestamp),
};
- this.host.recordMessageEdit(chatJid, revoked.id, '');
+ this.host.recordMessageEdit(chatJid, revoked.id, '', 'revoked');
// While the target is still being processed, the store change waits for it and lands after
// this delete is announced, and a repeat delivery may already hold the content in the store:
// record the delete now, checked against the target's own key.
@@ -635,9 +636,9 @@ export class BaileysEvents {
this.host.getOnMessage()?.(incoming);
}
}
- this.host.recordMessage(msg);
+ this.host.recordMessage(msg, incoming.type);
if (deleted) {
- this.host.recordMessageEdit(chatJid, storedId, '');
+ this.host.recordMessageEdit(chatJid, storedId, '', 'revoked');
} else if (editedBody !== undefined && storedId !== null) {
this.host.recordMessageEdit(chatJid, storedId, editedBody);
}
diff --git a/src/engine/adapters/baileys-history.ts b/src/engine/adapters/baileys-history.ts
index c7794be23..2af9ec7cb 100644
--- a/src/engine/adapters/baileys-history.ts
+++ b/src/engine/adapters/baileys-history.ts
@@ -1,6 +1,6 @@
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { Chat, Contact as BaileysContact, WAMessage, WASocket } from '@whiskeysockets/baileys';
-import { EngineEventCallbacks, IncomingMessage } from '../interfaces/whatsapp-engine.interface';
+import { EngineEventCallbacks, IncomingMessage, MessageType } from '../interfaces/whatsapp-engine.interface';
import {
BAILEYS_NON_CONTENT_TYPES,
buildIncomingMessageFromBaileys,
@@ -28,7 +28,7 @@ export interface BaileysHistoryHost {
/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */
loadLib(): Promise<typeof BaileysLib>;
/** Seed the chat's last-message preview + sort time from a history/live message. */
- recordMessage(msg: WAMessage): void;
+ recordMessage(msg: WAMessage, type?: MessageType): void;
upsertContacts(records: Partial<BaileysContact>[]): void;
upsertChats(records: Partial<Chat>[]): void;
/**
@@ -111,11 +111,10 @@ export class BaileysHistory {
nameUpdates.push({ id: sender, notify: msg.pushName });
}
}
- // Seed the chat's last-message preview + sort time (newest wins); else history-only chats
- // would read "No messages yet".
- this.host.recordMessage(msg);
const incoming = this.mapHistoryMessage(b, msg);
if (incoming) {
+ // Only content messages replace the preview; reactions and protocol updates do not.
+ this.host.recordMessage(msg, incoming.type);
mapped.push(incoming);
}
}
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index 1fc8fdc7d..f919ccab8 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -17,6 +17,7 @@ import {
LocationInput,
MediaInput,
MessageResult,
+ MessageType,
PollInput,
Product,
Quotable,
@@ -24,7 +25,14 @@ import {
import { toEngineParticipants } from './baileys-groups';
import { findSelfParticipant } from './baileys-group-mapper';
import { buildVCard } from './vcard';
-import { baileysChatJid, resolveBaileysButtonClick, setBaileysText, storedKeyInChat } from './baileys-message-mapper';
+import {
+ baileysChatJid,
+ isBaileysCatalogShare,
+ mapBaileysMessageType,
+ resolveBaileysButtonClick,
+ setBaileysText,
+ storedKeyInChat,
+} from './baileys-message-mapper';
import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';
import { BadRequestException, InternalServerErrorException } from '@nestjs/common';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
@@ -60,9 +68,9 @@ export interface BaileysMessagingHost {
/** Persist a just-sent message to the store; undefined when no store is configured. */
putStoredMessage(msg: WAMessage): Promise<void> | undefined;
/** Make a just-sent message the chat's last-message preview and sort time (its echo is skipped). */
- recordMessage(msg: WAMessage): void;
+ recordMessage(msg: WAMessage, type?: MessageType): void;
/** Replace the chat preview's text when the message is still the chat's last one (edit, or '' once deleted). */
- recordMessageEdit(chatId: string, messageId: string, text: string): void;
+ recordMessageEdit(chatId: string, messageId: string, text: string, type?: MessageType): void;
/** Record the id of a message this session just sent, so its library echo is recognised as ours. */
rememberOwnSend(id: string | null | undefined): void;
/** Look up a previously-seen message from the store (the reply/forward/react/delete handle). */
@@ -263,7 +271,7 @@ export class BaileysMessaging {
error: err instanceof Error ? err.message : String(err),
}),
);
- this.host.recordMessage(sent);
+ this.host.recordMessage(sent, 'text');
// Parity with the wwjs engine's message_create → message.sent (see emitOwnSendEcho).
void this.emitOwnSendEcho(sent);
}
@@ -594,7 +602,7 @@ export class BaileysMessaging {
const previewJid = baileysChatJid(chatJid, target.key.participant, target.key.fromMe === true);
if (forEveryone && (target.key.fromMe === true || (await this.selfIsGroupAdmin(target.key.remoteJid)) !== false)) {
await this.send(await this.toDeliverableJid(chatId), { delete: target.key });
- this.host.recordMessageEdit(previewJid, messageId, '');
+ this.host.recordMessageEdit(previewJid, messageId, '', 'revoked');
// The echo of this delete is skipped as an own send, so the stored copy is emptied here, as
// processInboundMessage does for a delete made from the phone or by the other side. Recorded
// first, so the message stays deleted even if the store write fails or a repeat delivery of the
@@ -620,7 +628,7 @@ export class BaileysMessaging {
),
'the delete-for-me',
);
- this.host.recordMessageEdit(previewJid, messageId, '');
+ this.host.recordMessageEdit(previewJid, messageId, '', 'revoked');
}
/**
@@ -770,6 +778,7 @@ export class BaileysMessaging {
content: AnyMessageContent,
options?: MiscMessageGenerationOptions,
): Promise<MessageResult> {
+ const b = await this.host.loadLib();
const jid = await this.toDeliverableJid(chatId);
const safe = this.previewSafe(content);
const merged = this.previewSafeOptions(safe, this.withEphemeral(jid, options));
@@ -780,7 +789,21 @@ export class BaileysMessaging {
error: err instanceof Error ? err.message : String(err),
}),
);
- this.host.recordMessage(sent);
+ // Preview metadata must not turn a completed send into a retryable failure.
+ let type: MessageType | undefined;
+ try {
+ if (sent.message) {
+ const normalized = b.normalizeMessageContent(sent.message) ?? sent.message;
+ type = mapBaileysMessageType(
+ b.getContentType(normalized),
+ normalized.audioMessage?.ptt === true,
+ isBaileysCatalogShare(normalized),
+ );
+ }
+ } catch (error) {
+ this.host.logger.warn('Failed to classify sent message preview', { error: String(error) });
+ }
+ this.host.recordMessage(sent, type);
// 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, which handleMessagesUpsert
// skips by the id send() recorded, so that event never fired for API sends. Emit the outbound
diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.ts
index 34403abdc..75989cf99 100644
--- a/src/engine/adapters/baileys-session-store.spec.ts
+++ b/src/engine/adapters/baileys-session-store.spec.ts
@@ -421,6 +421,33 @@ describe('BaileysSessionStore', () => {
});
});
+ it('keeps the latest type across older messages, edits, and revokes addressed through a twin', () => {
+ store.addLidMappings([{ lid: '999@lid', pn: '[email protected]' }]);
+ store.upsertChats([{ id: '999@lid' }]);
+ store.recordMessage(
+ { key: { remoteJid: '999@lid', id: 'LATEST' }, message: { imageMessage: {} }, messageTimestamp: 200 },
+ 'image',
+ );
+ store.recordMessage(
+ {
+ key: { remoteJid: '[email protected]', id: 'OLD' },
+ message: { conversation: 'old' },
+ messageTimestamp: 100,
+ },
+ 'text',
+ );
+ store.recordMessageEdit('[email protected]', 'LATEST', 'new caption');
+ expect(store.listChats()[0]).toMatchObject({
+ lastMessage: 'new caption',
+ lastMessageType: 'image',
+ timestamp: 200,
+ });
+ store.recordMessageEdit('[email protected]', 'OLD', '', 'revoked');
+ expect(store.listChats()[0].lastMessageType).toBe('image');
+ store.recordMessageEdit('[email protected]', 'LATEST', '', 'revoked');
+ expect(store.listChats()[0]).toMatchObject({ lastMessage: '', lastMessageType: 'revoked', timestamp: 200 });
+ });
+
it('does not overwrite a newer last-message with an older one', () => {
store.recordMessage({
key: { remoteJid: '[email protected]', id: 'NEW' },
diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.ts
index 37ae54eda..8a6436399 100644
--- a/src/engine/adapters/baileys-session-store.ts
+++ b/src/engine/adapters/baileys-session-store.ts
@@ -1,5 +1,5 @@
import type { Chat, Contact as BaileysContact, WAMessage, WAMessageKey } from '@whiskeysockets/baileys';
-import { ChatSummary, Contact } from '../interfaces/whatsapp-engine.interface';
+import { ChatSummary, Contact, MessageType } from '../interfaces/whatsapp-engine.interface';
import { chatKind, parseWaId, toNeutralJid as canonicalizeWaId, userPart } from '../identity/wa-id';
import type { LidMappingStore } from '../identity/lid-mapping-store.service';
import { mergeTwinStates, type ChatStateStore, type ChatStateValue } from './baileys-chat-state-store.service';
@@ -10,6 +10,7 @@ interface LastMessage {
key: WAMessageKey;
timestamp: number;
text: string;
+ type?: MessageType;
}
// Default per-map entry cap, matching the other per-session bounds (LID_MAPPING_CACHE_MAX,
@@ -417,7 +418,7 @@ export class BaileysSessionStore {
void this.lidStore?.remember(userPart(lidJid), userPart(pnJid), this.sessionId);
}
- recordMessage(msg: WAMessage): void {
+ recordMessage(msg: WAMessage, type?: MessageType): void {
const chatId = msg.key?.remoteJid;
if (!chatId || !msg.key) {
return;
@@ -438,7 +439,7 @@ export class BaileysSessionStore {
return; // keep the newest
}
const text = msg.message?.conversation ?? msg.message?.extendedTextMessage?.text ?? '';
- this.lastMessages.set(key, { key: msg.key, timestamp, text });
+ this.lastMessages.set(key, { key: msg.key, timestamp, text, type });
}
/**
@@ -446,11 +447,12 @@ export class BaileysSessionStore {
* that chat. Editing an older message must not replace the preview or reorder the conversation. The
* preview may sit on any twin of the chat, the one the listing reads included, so each is checked.
*/
- recordMessageEdit(chatId: string, messageId: string, text: string): void {
+ recordMessageEdit(chatId: string, messageId: string, text: string, type?: MessageType): void {
if (!messageId) return;
for (const key of new Set([this.chatKey(chatId), ...this.chatTwins(chatId)])) {
const existing = this.lastMessages.get(key);
- if (existing?.key.id === messageId) this.lastMessages.set(key, { ...existing, text });
+ if (existing?.key.id === messageId)
+ this.lastMessages.set(key, { ...existing, text, type: type ?? existing.type });
}
}
@@ -819,6 +821,7 @@ export class BaileysSessionStore {
?.unreadCount ?? 0,
timestamp: last?.timestamp ?? Math.max(...records.map(r => this.toUnixSeconds(r.conversationTimestamp))),
lastMessage: last?.text,
+ lastMessageType: last?.type,
archived: st ? st.archived : (c.archived ?? false),
// Baileys reports a pin as an ORDER, not a flag: 0/absent means unpinned.
pinned: st ? st.pinned : Boolean(c.pinned),
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 94b46a391..9fec78bd5 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -6312,12 +6312,101 @@ describe('BaileysAdapter contact + chat reads', () => {
unreadCount: 1,
timestamp: 1700000010,
lastMessage: 'hi',
+ lastMessageType: 'text',
archived: false,
pinned: false,
muted: false,
});
});
+ it.each(['live', 'history', 'API'] as const)('exposes wrapped media types from %s messages', async path => {
+ const adapter = await ready();
+ const baileys = jest.requireMock<Record<string, jest.Mock>>('@whiskeysockets/baileys');
+ const messages = [
+ {
+ key: { remoteJid: '[email protected]', id: 'PHOTO', fromMe: path === 'API' },
+ message: { ephemeralMessage: { message: { imageMessage: {} } } },
+ messageTimestamp: 1700000100,
+ },
+ {
+ key: { remoteJid: '[email protected]', id: 'VOICE', fromMe: path === 'API' },
+ message: { audioMessage: { ptt: true } },
+ messageTimestamp: 1700000200,
+ },
+ ];
+ baileys.getContentType.mockImplementation(realGetContentType);
+ baileys.normalizeMessageContent.mockImplementation(
+ (m?: { ephemeralMessage?: { message?: unknown } }) => m?.ephemeralMessage?.message ?? m,
+ );
+ const chats = messages.map(m => ({ id: m.key.remoteJid }));
+ fakeSock.fire('chats.upsert', chats);
+ if (path === 'API') {
+ fakeSock.sendMessage.mockResolvedValueOnce(messages[0]);
+ await adapter.sendImageMessage('[email protected]', { data: Buffer.from('photo'), mimetype: 'image/jpeg' });
+ fakeSock.sendMessage.mockResolvedValueOnce(messages[1]);
+ await adapter.sendAudioMessage('[email protected]', {
+ data: Buffer.from('voice'),
+ mimetype: 'audio/ogg',
+ ptt: true,
+ });
+ } else if (path === 'history') {
+ fakeSock.fire('messaging-history.set', { chats, contacts: [], messages });
+ } else {
+ fakeSock.fire('messages.upsert', { type: 'notify', messages });
+ }
+ await new Promise(r => setImmediate(r));
+ await new Promise(r => setImmediate(r));
+ const listed = await adapter.getChats();
+ expect(listed.find(c => c.id === '[email protected]')?.lastMessageType).toBe('image');
+ expect(listed.find(c => c.id === '[email protected]')?.lastMessageType).toBe('voice');
+ });
+
+ it('keeps the content preview when newer history entries only modify messages', async () => {
+ const adapter = await ready();
+ const baileys = jest.requireMock<Record<string, jest.Mock>>('@whiskeysockets/baileys');
+ baileys.getContentType.mockImplementation(realGetContentType);
+ fakeSock.fire('messaging-history.set', {
+ contacts: [],
+ chats: [{ id: '[email protected]' }],
+ messages: [
+ {
+ key: { remoteJid: '[email protected]', id: 'PHOTO' },
+ message: { imageMessage: {} },
+ messageTimestamp: 100,
+ },
+ {
+ key: { remoteJid: '[email protected]', id: 'REACTION' },
+ message: { reactionMessage: { text: 'ok' } },
+ messageTimestamp: 200,
+ },
+ {
+ key: { remoteJid: '[email protected]', id: 'PROTOCOL' },
+ message: { protocolMessage: { type: 3 } },
+ messageTimestamp: 300,
+ },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ expect((await adapter.getChats())[0]).toMatchObject({ lastMessageType: 'image', timestamp: 100 });
+ });
+
+ it('keeps a successful send successful when preview classification fails', async () => {
+ const adapter = await ready();
+ const baileys = jest.requireMock<Record<string, jest.Mock>>('@whiskeysockets/baileys');
+ fakeSock.sendMessage.mockResolvedValueOnce({
+ key: { id: 'OUT', remoteJid: '[email protected]' },
+ message: { imageMessage: {} },
+ messageTimestamp: 100,
+ });
+ baileys.normalizeMessageContent.mockImplementationOnce(() => {
+ throw new Error('unavailable metadata');
+ });
+ await expect(
+ adapter.sendImageMessage('[email protected]', { data: Buffer.from('photo'), mimetype: 'image/jpeg' }),
+ ).resolves.toEqual({ id: 'OUT', timestamp: 100 });
+ expect(fakeSock.sendMessage).toHaveBeenCalledTimes(1);
+ });
+
it('populates from messaging-history.set incl. lid mappings', async () => {
const adapter = await ready();
fakeSock.fire('messaging-history.set', {
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index cd67c21d0..38edbc8b1 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -140,8 +140,9 @@ export class BaileysAdapter implements IWhatsAppEngine {
toUnixSeconds,
inboundLimiter: this.inboundLimiter,
recordKeyLidMappings: key => this.sessionStore.recordKeyLidMappings(key),
- recordMessage: msg => this.sessionStore.recordMessage(msg),
- recordMessageEdit: (chatId, messageId, text) => this.sessionStore.recordMessageEdit(chatId, messageId, text),
+ recordMessage: (msg, type) => this.sessionStore.recordMessage(msg, type),
+ recordMessageEdit: (chatId, messageId, text, type) =>
+ this.sessionStore.recordMessageEdit(chatId, messageId, text, type),
putStoredMessage: msg => this.config.messageStore?.put(this.config.dbSessionId, msg),
updateStoredMessage: (messageId, change) =>
this.config.messageStore?.update(this.config.dbSessionId, messageId, change),
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index f5c7820c5..a197b5050 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -8688,12 +8688,17 @@ describe('WhatsAppWebJsAdapter raw-id extraction hardening', () => {
it('getChatsByLabel skips an undefined entry (deleted chat behind the label) instead of a 500', async () => {
const getChatsByLabelId = jest
.fn()
- .mockResolvedValue([undefined, { id: { _serialized: '[email protected]' }, name: 'Kept', isGroup: false }, { id: {} }]);
+ .mockResolvedValue([
+ undefined,
+ { id: { _serialized: '[email protected]' }, name: 'Kept', isGroup: false, lastMessage: { type: 'image' } },
+ { id: {} },
+ ]);
const result = await readyAdapter({ getChatsByLabelId }).getChatsByLabel('7');
expect(result).toHaveLength(1);
expect(result[0].id).toBe('[email protected]');
+ expect(result[0].lastMessageType).toBe('image');
});
// getNumberId returns a raw page-context Wid; on a WA Web build that renamed _serialized to $1,
diff --git a/src/engine/adapters/wwebjs-chats-read.spec.ts b/src/engine/adapters/wwebjs-chats-read.spec.ts
index 79f6ecbc1..61e983e47 100644
--- a/src/engine/adapters/wwebjs-chats-read.spec.ts
+++ b/src/engine/adapters/wwebjs-chats-read.spec.ts
@@ -124,6 +124,7 @@ describe('the chat and group lists read the page walk', () => {
unreadCount: 2,
timestamp: 1_700_000_000,
lastMessage: 'hello',
+ lastMessageType: 'text',
archived: true,
pinned: true,
muted: false,
@@ -131,6 +132,23 @@ describe('the chat and group lists read the page walk', () => {
expect(summaries[1]).toMatchObject({ id: '[email protected]', name: 'Team', isGroup: true });
});
+ it.each([
+ ['image', 'image'],
+ ['ptt', 'voice'],
+ ['audio', 'audio'],
+ ['document', 'document'],
+ ['new_engine_kind', 'unknown'],
+ ])('reports %s without needing preview text', async (rawType, type) => {
+ const { host } = makeHost([
+ { ...personal, lastMessage: { ...personal.lastMessage, type: rawType, body: '' } },
+ group,
+ ]);
+ const summaries = await new WwebjsChats(host, {} as WwebjsMessaging).getChats();
+ expect(summaries[0]).toMatchObject({ lastMessageType: type });
+ expect(summaries[0].lastMessage).toBeUndefined();
+ expect(summaries[1].lastMessageType).toBeUndefined();
+ });
+
it('getGroups keeps only groups, with participants, admin flag and linked parent', async () => {
const { host, evaluate, getChats } = makeHost([personal, group]);
diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.ts
index cb6f597e7..dacc420af 100644
--- a/src/engine/adapters/wwebjs-chats.ts
+++ b/src/engine/adapters/wwebjs-chats.ts
@@ -7,6 +7,7 @@ import { chatKind, isChannelJid } from '../identity/wa-id';
import { WwebjsMessaging } from './wwebjs-messaging';
import { type WwebjsEngineHost } from './wwebjs-host';
import { isProtocolTimeout } from './wwebjs-lifecycle';
+import { mapWwebjsMessageType } from './message-mapper';
/**
* Build the chat list IN-PAGE with the same `window.WWebJS.getChatModel` whatsapp-web.js's own
@@ -116,6 +117,7 @@ export class WwebjsChats {
timestamp: chat.timestamp || 0,
// A location message's body is the base64 map thumbnail; don't surface it as the chat preview.
lastMessage: chat.lastMessage?.type === MessageTypes.LOCATION ? '📍' : chat.lastMessage?.body || undefined,
+ lastMessageType: chat.lastMessage ? mapWwebjsMessageType(chat.lastMessage.type) : undefined,
archived: Boolean(chat.archived),
pinned: Boolean(chat.pinned),
// Chat.isMuted is the current verdict; muteExpiration is wwjs epoch SECONDS with -1 = forever.
diff --git a/src/engine/adapters/wwebjs-labels.ts b/src/engine/adapters/wwebjs-labels.ts
index c66322f01..1ed2b588d 100644
--- a/src/engine/adapters/wwebjs-labels.ts
+++ b/src/engine/adapters/wwebjs-labels.ts
@@ -1,5 +1,6 @@
import { NotFoundException } from '@nestjs/common';
import { type Client } from 'whatsapp-web.js';
+import { mapWwebjsMessageType } from './message-mapper';
import { Label, ChatSummary } from '../interfaces/whatsapp-engine.interface';
import { GroupChat, BusinessClient } from '../types/whatsapp-web-js.types';
import { isChannelJid, chatKind } from '../identity/wa-id';
@@ -82,6 +83,7 @@ export class WwebjsLabels {
kind: chatKind(id),
unreadCount: chat.unreadCount || 0,
timestamp: chat.timestamp || 0,
+ lastMessageType: chat.lastMessage ? mapWwebjsMessageType(chat.lastMessage.type) : undefined,
archived: Boolean(chat.archived),
pinned: Boolean(chat.pinned),
muted: Boolean(chat.isMuted),
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index e9141d50d..8e534ef4a 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -553,6 +553,8 @@ export interface ChatSummary {
unreadCount: number;
timestamp: number;
lastMessage?: string;
+ /** Engine-neutral type of the last message, when available. */
+ lastMessageType?: MessageType;
/** Archived state, as set via `POST /sessions/{sessionId}/chats/archive`. */
archived: boolean;
/** Pinned state, as set via `POST /sessions/{sessionId}/chats/pin`. */
diff --git a/src/engine/types/whatsapp-web-js.types.ts b/src/engine/types/whatsapp-web-js.types.ts
index ff6e81eb3..7b7c34a50 100644
--- a/src/engine/types/whatsapp-web-js.types.ts
+++ b/src/engine/types/whatsapp-web-js.types.ts
@@ -140,6 +140,7 @@ export interface BusinessClient extends Omit<
pinned?: boolean;
isMuted?: boolean;
muteExpiration?: number;
+ lastMessage?: { type: string };
}
| undefined
>
diff --git a/src/modules/session/dto/chat-summary.dto.ts b/src/modules/session/dto/chat-summary.dto.ts
index 69359719d..457486e20 100644
--- a/src/modules/session/dto/chat-summary.dto.ts
+++ b/src/modules/session/dto/chat-summary.dto.ts
@@ -1,5 +1,7 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import type { ChatKind } from '../../../engine/identity/wa-id';
+import type { MessageType } from '../../../engine/interfaces/whatsapp-engine.interface';
+import { MESSAGE_TYPES } from '../../webhook/filters/filter-types';
const CHAT_KINDS: ChatKind[] = ['individual', 'group', 'channel', 'status', 'broadcast', 'unknown'];
@@ -26,6 +28,13 @@ export class ChatSummaryDto {
@ApiPropertyOptional({ example: 'hi' })
lastMessage?: string;
+ @ApiPropertyOptional({
+ enum: MESSAGE_TYPES,
+ description: 'Engine-neutral type of the last message, when available.',
+ example: 'image',
+ })
+ lastMessageType?: MessageType;
+
@ApiProperty({ description: 'Archived state, as set via POST /sessions/{sessionId}/chats/archive.', example: false })
archived!: boolean;