Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat: add sender display names (#782)

Aldino Kemal91d27b1e3849
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index bf00f372..36b6dbe8 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -5185,6 +5185,16 @@ components:
type: string
example: '[email protected]'
description: Sender JID
+ sender_display_name:
+ type: string
+ example: 'Saved Contact'
+ description: >-
+ Human-readable sender label resolved dynamically when this response is produced, not stored with the message.
+ For other senders, it prefers the saved contact full name, then the stored contact push name, business name,
+ JID user part, and raw JID. For the active account, it prefers the device display name (falling back to the
+ stored account push name), account JID user part, account JID, sender JID user part, and raw sender JID.
+ A contact rename can therefore change the label returned for historical messages. `sender_jid` remains the
+ stable sender identifier.
content:
type: string
example: 'Hello, how are you?'
@@ -5249,6 +5259,16 @@ components:
type: string
example: '[email protected]'
description: JID of the user who reacted
+ sender_display_name:
+ type: string
+ example: 'Saved Contact'
+ description: >-
+ Human-readable sender label resolved dynamically when this response is produced, not stored with the reaction.
+ For other senders, it prefers the saved contact full name, then the stored contact push name, business name,
+ JID user part, and raw JID. For the active account, it prefers the device display name (falling back to the
+ stored account push name), account JID user part, account JID, sender JID user part, and raw sender JID.
+ A contact rename can therefore change the label returned for historical reactions. `sender_jid` remains the
+ stable sender identifier.
is_from_me:
type: boolean
example: false
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index 01b4b9c9..3fae6ba4 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -199,10 +199,25 @@ Fields commonly found inside the `payload` object:
| `chat_id` | string | Chat JID (e.g., `[email protected]` or `[email protected]` for groups) |
| `from` | string | Full JID of the sender (e.g., `[email protected]`) |
| `from_lid` | string | LID (Linked ID) of the sender if available |
-| `from_name` | string | Display name (pushname) of the sender |
+| `sender_display_name` | string | Dynamic human-readable sender label. Present only when `from` is a non-empty string; see [Sender Display Name Resolution](#sender-display-name-resolution). |
+| `from_name` | string | Legacy message-event push name of the sender. It remains available for compatibility and is not replaced by `sender_display_name`. |
| `timestamp` | string | RFC3339 formatted timestamp (e.g., `2023-10-15T10:30:00Z`) |
| `is_from_me` | boolean | Whether the message was sent by the current user |
+### Sender Display Name Resolution
+
+`sender_display_name` is added only when `payload.from` is a non-empty string. It is omitted when `from` is missing,
+empty, or not a singular string. Resolution is best-effort and never prevents a webhook from being delivered: a contact
+lookup failure falls through the remaining applicable precedence candidates (including a live event push name when
+available), then deterministically to the JID user part, or to the original `from` value when it cannot be parsed.
+
+For another sender, the resolver prefers the saved contact full name, then the live WhatsApp push name supplied by the
+event (when available), the stored contact push name, the contact business name, and the JID user part. For the active
+account, it prefers the stored account push name, account JID user part, account JID, sender JID user part, and raw
+sender JID. The label is resolved at webhook-build time, so a saved-contact rename can change labels on later events.
+`from_name` remains the legacy message-event push name; it is a separate compatibility field and does not use this
+resolution order.
+
## Message Events
### Text Message
@@ -216,6 +231,7 @@ Fields commonly found inside the `payload` object:
"chat_id": "[email protected]",
"from": "[email protected]",
"from_lid": "251556368777322@lid",
+ "sender_display_name": "Saved Contact",
"from_name": "John Doe",
"timestamp": "2023-10-15T10:30:00Z",
"is_from_me": false,
@@ -234,6 +250,7 @@ Fields commonly found inside the `payload` object:
"id": "3EB0C127D7BACC83D6A2",
"chat_id": "[email protected]",
"from": "[email protected]",
+ "sender_display_name": "Saved Contact",
"from_name": "John Doe",
"timestamp": "2023-10-15T10:35:00Z",
"is_from_me": false,
@@ -254,6 +271,7 @@ Fields commonly found inside the `payload` object:
"id": "88760C69D1F35FEB239102699AE9XXXX",
"chat_id": "[email protected]",
"from": "[email protected]",
+ "sender_display_name": "Saved Contact",
"from_name": "John Doe",
"timestamp": "2023-10-15T10:40:00Z",
"is_from_me": false,
@@ -284,6 +302,7 @@ Triggered when a message is successfully delivered to the recipient's device.
"chat_id": "[email protected]",
"from": "[email protected]",
"from_lid": "251556368777322@lid",
+ "sender_display_name": "Saved Contact",
"receipt_type": "delivered",
"receipt_type_description": "means the message was delivered to the device (but the user might not have noticed)."
}
@@ -305,6 +324,7 @@ Triggered when a message is read by the recipient (they opened the chat and saw
],
"chat_id": "[email protected]",
"from": "[email protected]",
+ "sender_display_name": "Saved Contact",
"receipt_type": "read",
"receipt_type_description": "the user opened the chat and saw the message."
}
@@ -322,6 +342,7 @@ Triggered when a message is read by the recipient (they opened the chat and saw
| `payload.chat_id` | string | Chat identifier (group or individual chat) |
| `payload.from` | string | JID of the user who triggered the receipt |
| `payload.from_lid` | string | LID of the user (if available) |
+| `payload.sender_display_name` | string | Dynamic sender label when `payload.from` is non-empty |
| `payload.receipt_type` | string | Type of receipt: `"delivered"`, `"read"`, etc. |
| `payload.receipt_type_description` | string | Human-readable description of the receipt type |
@@ -345,6 +366,7 @@ Triggered when a user starts typing a text message.
"timestamp": "2026-01-22T12:00:00Z",
"payload": {
"from": "[email protected]",
+ "sender_display_name": "Saved Contact",
"chat_id": "[email protected]",
"state": "composing",
"media": "",
@@ -364,6 +386,7 @@ Triggered when a user stops typing (pauses or clears the input field).
"timestamp": "2026-01-22T12:00:05Z",
"payload": {
"from": "[email protected]",
+ "sender_display_name": "Saved Contact",
"chat_id": "[email protected]",
"state": "paused",
"media": "",
@@ -383,6 +406,7 @@ Triggered when a user starts recording a voice message.
"timestamp": "2026-01-22T12:01:00Z",
"payload": {
"from": "[email protected]",
+ "sender_display_name": "Saved Contact",
"chat_id": "[email protected]",
"state": "composing",
"media": "audio",
@@ -403,6 +427,7 @@ Triggered when a user starts typing in a group chat.
"payload": {
"from": "[email protected]",
"from_lid": "251556368777322@lid",
+ "sender_display_name": "Saved Contact",
"chat_id": "[email protected]",
"state": "composing",
"media": "",
@@ -420,6 +445,7 @@ Triggered when a user starts typing in a group chat.
| `timestamp` | string | RFC3339 formatted timestamp when the event was processed |
| `payload.from` | string | JID of the user who is typing (e.g., `[email protected]`)|
| `payload.from_lid` | string | LID of the user (if available, typically in group chats) |
+| `payload.sender_display_name` | string | Dynamic sender label when `payload.from` is non-empty |
| `payload.chat_id` | string | Chat identifier (individual or group) |
| `payload.state` | string | Typing state: `"composing"` (typing) or `"paused"` (stopped) |
| `payload.media` | string | Media type: `""` (text message) or `"audio"` (voice recording) |
@@ -706,6 +732,7 @@ Triggered when an incoming call is received.
"payload": {
"call_id": "ABC123DEF456",
"from": "[email protected]",
+ "sender_display_name": "Saved Contact",
"auto_rejected": false,
"remote_platform": "android",
"remote_version": "2.24.1.5"
@@ -725,6 +752,7 @@ When `WHATSAPP_AUTO_REJECT_CALL=true`, calls are automatically rejected and the
"payload": {
"call_id": "ABC123DEF456",
"from": "[email protected]",
+ "sender_display_name": "Saved Contact",
"auto_rejected": true,
"remote_platform": "android",
"remote_version": "2.24.1.5",
@@ -742,6 +770,7 @@ When `WHATSAPP_AUTO_REJECT_CALL=true`, calls are automatically rejected and the
| `timestamp` | string | RFC3339 formatted timestamp when the call was received |
| `payload.call_id` | string | Unique identifier for the call |
| `payload.from` | string | JID of the caller |
+| `payload.sender_display_name` | string | Dynamic sender label when `payload.from` is non-empty |
| `payload.auto_rejected` | boolean | Whether the call was auto-rejected |
| `payload.remote_platform` | string | Platform of the caller (e.g., `"android"`, `"ios"`) |
| `payload.remote_version` | string | WhatsApp version of the caller |
@@ -794,6 +823,7 @@ When you receive a `call.offer` webhook event, extract the values from the paylo
"payload": {
"call_id": "ABC123DEF456",
"from": "[email protected]",
+ "sender_display_name": "Saved Contact",
"auto_rejected": false
}
}
@@ -1161,6 +1191,7 @@ Triggered when a message is deleted for the current user (DeleteForMe event).
"deleted_message_id": "3EB0C127D7BACC83D6A1",
"timestamp": "2025-07-13T11:12:00Z",
"from": "[email protected]",
+ "sender_display_name": "Saved Contact",
"chat_id": "[email protected]",
"original_content": "Hello, how are you?",
"original_sender": "[email protected]",
@@ -1177,6 +1208,7 @@ Triggered when a message is deleted for the current user (DeleteForMe event).
| `payload.deleted_message_id` | string | ID of the deleted message |
| `payload.timestamp` | string | RFC3339 timestamp when the delete event occurred |
| `payload.from` | string | JID of the user who deleted the message |
+| `payload.sender_display_name` | string | Dynamic sender label when `payload.from` is non-empty |
| `payload.chat_id` | string | Chat identifier where the message was deleted |
| `payload.original_content` | string | Original message content (if available from storage) |
| `payload.original_sender` | string | Original sender of the deleted message |
diff --git a/src/domains/chat/chat.go b/src/domains/chat/chat.go
index b3df4612..3ac8c361 100644
--- a/src/domains/chat/chat.go
+++ b/src/domains/chat/chat.go
@@ -56,14 +56,15 @@ type ChatInfo struct {
}
type MessageInfo struct {
- ID string `json:"id"`
- ChatJID string `json:"chat_jid"`
- SenderJID string `json:"sender_jid"`
- Content string `json:"content"`
- Timestamp string `json:"timestamp"`
- IsFromMe bool `json:"is_from_me"`
- MediaType string `json:"media_type"`
- Reactions []ReactionInfo `json:"reactions,omitempty"`
+ ID string `json:"id"`
+ ChatJID string `json:"chat_jid"`
+ SenderJID string `json:"sender_jid"`
+ SenderDisplayName string `json:"sender_display_name"`
+ Content string `json:"content"`
+ Timestamp string `json:"timestamp"`
+ IsFromMe bool `json:"is_from_me"`
+ MediaType string `json:"media_type"`
+ Reactions []ReactionInfo `json:"reactions,omitempty"`
// CallMetadata is JSON when media_type is "call" (incoming call log).
CallMetadata string `json:"call_metadata,omitempty"`
Filename string `json:"filename"`
diff --git a/src/domains/chat/reaction.go b/src/domains/chat/reaction.go
index 0f3183ca..e7af7200 100644
--- a/src/domains/chat/reaction.go
+++ b/src/domains/chat/reaction.go
@@ -2,8 +2,9 @@ package chat
// ReactionInfo represents a single emoji reaction attached to a message.
type ReactionInfo struct {
- Emoji string `json:"emoji"`
- SenderJID string `json:"sender_jid"`
- IsFromMe bool `json:"is_from_me"`
- Timestamp string `json:"timestamp"`
+ Emoji string `json:"emoji"`
+ SenderJID string `json:"sender_jid"`
+ SenderDisplayName string `json:"sender_display_name"`
+ IsFromMe bool `json:"is_from_me"`
+ Timestamp string `json:"timestamp"`
}
diff --git a/src/infrastructure/whatsapp/event_call.go b/src/infrastructure/whatsapp/event_call.go
index 86f8af45..c7d210ee 100644
--- a/src/infrastructure/whatsapp/event_call.go
+++ b/src/infrastructure/whatsapp/event_call.go
@@ -59,7 +59,13 @@ func createCallOfferPayload(ctx context.Context, evt *events.CallOffer, deviceID
// Add call details
payload["call_id"] = evt.CallID
- payload["from"] = evt.CallCreator.ToNonAD().String()
+ senderJID := evt.CallCreator
+ if senderJID.Server == "lid" {
+ payload["from_lid"] = senderJID.ToNonAD().String()
+ }
+ normalizedSenderJID := NormalizeJIDFromLID(ctx, senderJID, client)
+ payload["from"] = normalizedSenderJID.ToNonAD().String()
+ addSenderDisplayName(ctx, client, payload, false, "")
payload["auto_rejected"] = autoRejected
// Add caller platform info if available
diff --git a/src/infrastructure/whatsapp/event_chat_presence.go b/src/infrastructure/whatsapp/event_chat_presence.go
index c12e04dd..92a6fec5 100644
--- a/src/infrastructure/whatsapp/event_chat_presence.go
+++ b/src/infrastructure/whatsapp/event_chat_presence.go
@@ -46,6 +46,7 @@ func createChatPresencePayload(ctx context.Context, evt *events.ChatPresence, de
}
normalizedSenderJID := NormalizeJIDFromLID(ctx, senderJID, client)
payload["from"] = normalizedSenderJID.ToNonAD().String()
+ addSenderDisplayName(ctx, client, payload, false, "")
// Chat where the presence event occurred
payload["chat_id"] = evt.Chat.ToNonAD().String()
diff --git a/src/infrastructure/whatsapp/event_delete.go b/src/infrastructure/whatsapp/event_delete.go
index 38a319d2..efd38d33 100644
--- a/src/infrastructure/whatsapp/event_delete.go
+++ b/src/infrastructure/whatsapp/event_delete.go
@@ -30,6 +30,7 @@ func createDeletePayload(ctx context.Context, evt *events.DeleteForMe, message *
// Resolve sender JID (convert LID to phone number if needed)
normalizedSenderJID := NormalizeJIDFromLID(ctx, evt.SenderJID, client)
payload["from"] = normalizedSenderJID.ToNonAD().String()
+ addSenderDisplayName(ctx, client, payload, false, "")
// Include original message information if available
if message != nil {
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index cda101a1..64cde230 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -100,6 +100,7 @@ func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *event
// Build from/from_lid fields
buildFromFields(ctx, client, evt, payload)
+ addSenderDisplayName(ctx, client, payload, evt.Info.IsFromMe, evt.Info.PushName)
// Set from_name (pushname)
if pushname := evt.Info.PushName; pushname != "" {
diff --git a/src/infrastructure/whatsapp/event_message_test.go b/src/infrastructure/whatsapp/event_message_test.go
index 2f00ebdd..78690967 100644
--- a/src/infrastructure/whatsapp/event_message_test.go
+++ b/src/infrastructure/whatsapp/event_message_test.go
@@ -7,8 +7,10 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
"github.com/stretchr/testify/assert"
+ "go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/proto/waCommon"
"go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
)
@@ -419,3 +421,110 @@ func TestBuildEventPayloadContactsArrayIncludesPhoneNumbers(t *testing.T) {
t.Fatalf("expected second phone number, got %q", contacts[1].PhoneNumber)
}
}
+
+func TestBuildEventPayloadIncludesSenderDisplayName(t *testing.T) {
+ accountJID := types.NewJID("628111111111", types.DefaultUserServer)
+ senderJID := types.NewJID("628123456789", types.DefaultUserServer)
+ contacts := &senderDisplayNameContactGetter{
+ contacts: map[types.JID]types.ContactInfo{
+ senderJID: {
+ Found: true,
+ FullName: "Saved Contact",
+ },
+ },
+ }
+ client := &whatsmeow.Client{
+ Store: &store.Device{
+ ID: &accountJID,
+ PushName: "Active Account",
+ Contacts: contacts,
+ },
+ }
+
+ tests := []struct {
+ name string
+ isFromMe bool
+ sender types.JID
+ message *waE2E.Message
+ wantEvent string
+ wantName string
+ }{
+ {
+ name: "message",
+ sender: senderJID,
+ message: &waE2E.Message{Conversation: protoString("hello")},
+ wantEvent: EventTypeMessage,
+ wantName: "Saved Contact",
+ },
+ {
+ name: "reaction before early return",
+ sender: senderJID,
+ message: &waE2E.Message{ReactionMessage: &waE2E.ReactionMessage{
+ Key: &waCommon.MessageKey{
+ RemoteJID: protoString("[email protected]"),
+ ID: protoString("target-message"),
+ },
+ Text: protoString("👍"),
+ }},
+ wantEvent: EventTypeMessageReaction,
+ wantName: "Saved Contact",
+ },
+ {
+ name: "revoke before early return",
+ sender: senderJID,
+ message: &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{
+ Type: protoProtocolMessageType(waE2E.ProtocolMessage_REVOKE),
+ Key: &waCommon.MessageKey{ID: protoString("revoked-message")},
+ }},
+ wantEvent: EventTypeMessageRevoked,
+ wantName: "Saved Contact",
+ },
+ {
+ name: "edit before early return",
+ sender: senderJID,
+ message: &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{
+ Type: protoProtocolMessageType(waE2E.ProtocolMessage_MESSAGE_EDIT),
+ Key: &waCommon.MessageKey{ID: protoString("edited-message")},
+ EditedMessage: &waE2E.Message{
+ Conversation: protoString("updated"),
+ },
+ }},
+ wantEvent: EventTypeMessageEdited,
+ wantName: "Saved Contact",
+ },
+ {
+ name: "outgoing active account",
+ isFromMe: true,
+ sender: accountJID,
+ message: &waE2E.Message{Conversation: protoString("hello")},
+ wantEvent: EventTypeMessage,
+ wantName: "Active Account",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ evt := &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: types.NewJID("628100000000", types.DefaultUserServer),
+ Sender: tt.sender,
+ IsFromMe: tt.isFromMe,
+ },
+ ID: "sender-display-name",
+ PushName: "Live Push",
+ Timestamp: time.Date(2026, time.July, 28, 10, 0, 0, 0, time.UTC),
+ },
+ Message: tt.message,
+ }
+
+ eventType, payload, err := buildEventPayload(context.Background(), client, evt)
+
+ assert.NoError(t, err)
+ assert.Equal(t, tt.wantEvent, eventType)
+ assert.Equal(t, tt.sender.String(), payload["from"])
+ assert.Equal(t, "Live Push", payload["from_name"])
+ assert.Equal(t, tt.wantName, payload["sender_display_name"])
+ })
+ }
+}
diff --git a/src/infrastructure/whatsapp/event_receipt.go b/src/infrastructure/whatsapp/event_receipt.go
index 16be3879..6f68a7e6 100644
--- a/src/infrastructure/whatsapp/event_receipt.go
+++ b/src/infrastructure/whatsapp/event_receipt.go
@@ -57,6 +57,7 @@ func createReceiptPayload(ctx context.Context, evt *events.Receipt, deviceID str
// Resolve sender JID (convert LID to phone number if needed)
normalizedSenderJID := NormalizeJIDFromLID(ctx, senderJID, client)
payload["from"] = normalizedSenderJID.ToNonAD().String()
+ addSenderDisplayName(ctx, client, payload, false, "")
// Receipt type
if evt.Type == types.ReceiptTypeDelivered {
diff --git a/src/infrastructure/whatsapp/event_sender_display_name_test.go b/src/infrastructure/whatsapp/event_sender_display_name_test.go
new file mode 100644
index 00000000..67198c82
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_sender_display_name_test.go
@@ -0,0 +1,176 @@
+package whatsapp
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+ waLog "go.mau.fi/whatsmeow/util/log"
+)
+
+type callOfferLIDStore struct {
+ store.NoopStore
+ phoneNumbers map[types.JID]types.JID
+}
+
+func (s *callOfferLIDStore) GetPNForLID(_ context.Context, lid types.JID) (types.JID, error) {
+ return s.phoneNumbers[lid], nil
+}
+
+func TestSenderBearingWebhookPayloadsIncludeSenderDisplayName(t *testing.T) {
+ accountJID := types.NewJID("628111111111", types.DefaultUserServer)
+ senderJID := types.NewJID("628123456789", types.DefaultUserServer)
+ client := &whatsmeow.Client{
+ Store: &store.Device{
+ ID: &accountJID,
+ PushName: "Active Account",
+ Contacts: &senderDisplayNameContactGetter{
+ contacts: map[types.JID]types.ContactInfo{
+ senderJID: {
+ Found: true,
+ FullName: "Saved Contact",
+ },
+ },
+ },
+ },
+ }
+
+ tests := []struct {
+ name string
+ build func(*testing.T) map[string]any
+ }{
+ {
+ name: "receipt",
+ build: func(*testing.T) map[string]any {
+ return createReceiptPayload(context.Background(), &events.Receipt{
+ MessageSource: types.MessageSource{
+ Chat: types.NewJID("628100000000", types.DefaultUserServer),
+ Sender: senderJID,
+ },
+ MessageIDs: []types.MessageID{"receipt-message"},
+ Timestamp: time.Date(2026, time.July, 28, 10, 0, 0, 0, time.UTC),
+ Type: types.ReceiptTypeRead,
+ }, accountJID.String(), client)
+ },
+ },
+ {
+ name: "delete",
+ build: func(t *testing.T) map[string]any {
+ t.Helper()
+ payload, err := createDeletePayload(context.Background(), &events.DeleteForMe{
+ SenderJID: senderJID,
+ MessageID: "deleted-message",
+ }, nil, accountJID.String(), client)
+ assert.NoError(t, err)
+ return payload
+ },
+ },
+ {
+ name: "chat presence",
+ build: func(*testing.T) map[string]any {
+ return createChatPresencePayload(context.Background(), &events.ChatPresence{
+ MessageSource: types.MessageSource{
+ Chat: types.NewJID("628100000000", types.DefaultUserServer),
+ Sender: senderJID,
+ },
+ State: types.ChatPresenceComposing,
+ }, accountJID.String(), client)
+ },
+ },
+ {
+ name: "call offer",
+ build: func(*testing.T) map[string]any {
+ return createCallOfferPayload(context.Background(), &events.CallOffer{
+ BasicCallMeta: types.BasicCallMeta{
+ CallCreator: senderJID,
+ CallID: "call-id",
+ Timestamp: time.Date(2026, time.July, 28, 10, 0, 0, 0, time.UTC),
+ },
+ }, accountJID.String(), client, false)
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ body := tt.build(t)
+ payload := body["payload"].(map[string]any)
+
+ assert.Equal(t, senderJID.String(), payload["from"])
+ assert.Equal(t, "Saved Contact", payload["sender_display_name"])
+ })
+ }
+}
+
+func TestCreateCallOfferPayloadNormalizesCaller(t *testing.T) {
+ originalLog := log
+ log = waLog.Noop
+ defer func() { log = originalLog }()
+
+ accountJID := types.NewJID("628111111111", types.DefaultUserServer)
+ lidCaller := types.NewJID("251556368777322", types.HiddenUserServer)
+ phoneCaller := types.NewJID("628123456789", types.DefaultUserServer)
+ client := &whatsmeow.Client{
+ Store: &store.Device{
+ ID: &accountJID,
+ Contacts: &senderDisplayNameContactGetter{
+ contacts: map[types.JID]types.ContactInfo{
+ phoneCaller: {
+ Found: true,
+ FullName: "Saved Caller",
+ },
+ },
+ },
+ LIDs: &callOfferLIDStore{
+ phoneNumbers: map[types.JID]types.JID{
+ lidCaller: phoneCaller,
+ },
+ },
+ },
+ }
+
+ tests := []struct {
+ name string
+ caller types.JID
+ wantFrom string
+ wantFromLID string
+ }{
+ {
+ name: "LID caller",
+ caller: lidCaller,
+ wantFrom: "[email protected]",
+ wantFromLID: "251556368777322@lid",
+ },
+ {
+ name: "non-LID caller",
+ caller: phoneCaller,
+ wantFrom: "[email protected]",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ body := createCallOfferPayload(context.Background(), &events.CallOffer{
+ BasicCallMeta: types.BasicCallMeta{
+ CallCreator: tt.caller,
+ CallID: "call-id",
+ Timestamp: time.Date(2026, time.July, 29, 10, 0, 0, 0, time.UTC),
+ },
+ }, accountJID.String(), client, false)
+ payload := body["payload"].(map[string]any)
+
+ assert.Equal(t, tt.wantFrom, payload["from"])
+ assert.Equal(t, "Saved Caller", payload["sender_display_name"])
+ if tt.wantFromLID == "" {
+ assert.NotContains(t, payload, "from_lid")
+ } else {
+ assert.Equal(t, tt.wantFromLID, payload["from_lid"])
+ }
+ })
+ }
+}
diff --git a/src/infrastructure/whatsapp/sender_display_name.go b/src/infrastructure/whatsapp/sender_display_name.go
new file mode 100644
index 00000000..55097896
--- /dev/null
+++ b/src/infrastructure/whatsapp/sender_display_name.go
@@ -0,0 +1,203 @@
+package whatsapp
+
+import (
+ "context"
+ "strings"
+ "sync"
+
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/types"
+)
+
+// contactInfoGetter is the small subset of the WhatsApp contact store needed
+// to resolve a sender label.
+type contactInfoGetter interface {
+ GetContact(context.Context, types.JID) (types.ContactInfo, error)
+}
+
+// PreferredContactDisplayName applies the contact-name precedence shared by
+// sender labels. Candidates are returned verbatim; whitespace is only treated
+// as unavailable while choosing the next candidate.
+func PreferredContactDisplayName(contact types.ContactInfo, livePushName string) string {
+ for _, candidate := range []string{
+ contact.FullName,
+ livePushName,
+ contact.PushName,
+ contact.BusinessName,
+ } {
+ if hasDisplayName(candidate) {
+ return candidate
+ }
+ }
+ return ""
+}
+
+// SenderDisplayNameResolver resolves a stable, human-readable sender label.
+type SenderDisplayNameResolver struct {
+ contacts contactInfoGetter
+ client *whatsmeow.Client
+ accountJID types.JID
+ deviceDisplayName string
+}
+
+// NewSenderDisplayNameResolver creates a resolver for one active WhatsApp
+// client. A supplied device display name takes precedence for that account's
+// own messages; its stored push name is used only when no explicit name exists.
+func NewSenderDisplayNameResolver(client *whatsmeow.Client, deviceDisplayName string) *SenderDisplayNameResolver {
+ var contacts contactInfoGetter
+ var accountJID types.JID
+ if client != nil && client.Store != nil {
+ contacts = client.Store.Contacts
+ if client.Store.ID != nil {
+ accountJID = client.Store.ID.ToNonAD()
+ }
+ if !hasDisplayName(deviceDisplayName) {
+ deviceDisplayName = client.Store.PushName
+ }
+ }
+ return newSenderDisplayNameResolver(contacts, client, accountJID, deviceDisplayName)
+}
+
+func newSenderDisplayNameResolver(contacts contactInfoGetter, client *whatsmeow.Client, accountJID types.JID, deviceDisplayName string) *SenderDisplayNameResolver {
+ return &SenderDisplayNameResolver{
+ contacts: contacts,
+ client: client,
+ accountJID: accountJID.ToNonAD(),
+ deviceDisplayName: deviceDisplayName,
+ }
+}
+
+// Resolve returns the best available display name for senderJID. It never
+// exposes a contact-store failure: the JID's user part (or malformed input)
+// remains a deterministic fallback.
+func (r *SenderDisplayNameResolver) Resolve(ctx context.Context, senderJID string, isFromMe bool, livePushName string) string {
+ jid, validJID := r.normalizeJID(ctx, senderJID)
+ activeAccount := isFromMe || (validJID && r.isAccountJID(ctx, jid))
+
+ if activeAccount {
+ return r.activeAccountDisplayName(jid, validJID, senderJID)
+ }
+
+ var contact types.ContactInfo
+ if validJID && r.contacts != nil {
+ stored, err := r.contacts.GetContact(ctx, jid)
+ if err == nil && stored.Found {
+ contact = stored
+ if hasDisplayName(contact.FullName) {
+ return contact.FullName
+ }
+ }
+ }
+
+ if hasDisplayName(livePushName) {
+ return livePushName
+ }
+ if name := PreferredContactDisplayName(contact, ""); name != "" {
+ return name
+ }
+ if validJID && hasDisplayName(jid.User) {
+ return jid.User
+ }
+ return senderJID
+}
+
+func (r *SenderDisplayNameResolver) activeAccountDisplayName(senderJID types.JID, validSenderJID bool, rawSenderJID string) string {
+ if hasDisplayName(r.deviceDisplayName) {
+ return r.deviceDisplayName
+ }
+ if hasDisplayName(r.accountJID.User) {
+ return r.accountJID.User
+ }
+ if accountJID := r.accountJID.String(); accountJID != "" {
+ return accountJID
+ }
+ if validSenderJID && hasDisplayName(senderJID.User) {
+ return senderJID.User
+ }
+ if validSenderJID && senderJID.String() != "" {
+ return senderJID.String()
+ }
+ return rawSenderJID
+}
+
+func (r *SenderDisplayNameResolver) normalizeJID(ctx context.Context, senderJID string) (types.JID, bool) {
+ jid, err := types.ParseJID(senderJID)
+ if err != nil || jid.IsEmpty() || !hasDisplayName(jid.User) {
+ return types.EmptyJID, false
+ }
+ jid = jid.ToNonAD()
+ if jid.Server == types.HiddenUserServer && r.client != nil && r.client.Store != nil && r.client.Store.LIDs != nil {
+ jid = NormalizeJIDFromLID(ctx, jid, r.client).ToNonAD()
+ }
+ if jid.IsEmpty() || !hasDisplayName(jid.User) {
+ return types.EmptyJID, false
+ }
+ return jid, true
+}
+
+func (r *SenderDisplayNameResolver) isAccountJID(ctx context.Context, jid types.JID) bool {
+ if r.accountJID.IsEmpty() {
+ return false
+ }
+ accountJID := r.accountJID
+ if accountJID.Server == types.HiddenUserServer && r.client != nil && r.client.Store != nil && r.client.Store.LIDs != nil {
+ accountJID = NormalizeJIDFromLID(ctx, accountJID, r.client).ToNonAD()
+ }
+ return jid == accountJID
+}
+
+func (r *SenderDisplayNameResolver) cacheKey(ctx context.Context, senderJID string, isFromMe bool) string {
+ jid, validJID := r.normalizeJID(ctx, senderJID)
+ if isFromMe || (validJID && r.isAccountJID(ctx, jid)) {
+ return "self"
+ }
+ if validJID {
+ return jid.String()
+ }
+ return senderJID
+}
+
+func hasDisplayName(value string) bool {
+ return strings.TrimSpace(value) != ""
+}
+
+func addSenderDisplayName(ctx context.Context, client *whatsmeow.Client, payload map[string]any, isFromMe bool, livePushName string) {
+ senderJID, ok := payload["from"].(string)
+ if !ok || senderJID == "" {
+ return
+ }
+
+ resolver := NewSenderDisplayNameResolver(client, "")
+ payload["sender_display_name"] = resolver.Resolve(ctx, senderJID, isFromMe, livePushName)
+}
+
+// SenderDisplayNameCache memoizes labels for the lifetime of one response or
+// webhook payload build.
+type SenderDisplayNameCache struct {
+ resolver *SenderDisplayNameResolver
+ mu sync.Mutex
+ values map[string]string
+}
+
+func NewSenderDisplayNameCache(resolver *SenderDisplayNameResolver) *SenderDisplayNameCache {
+ return &SenderDisplayNameCache{
+ resolver: resolver,
+ values: make(map[string]string),
+ }
+}
+
+func (c *SenderDisplayNameCache) Resolve(ctx context.Context, senderJID string, isFromMe bool, livePushName string) string {
+ if c == nil || c.resolver == nil {
+ return senderJID
+ }
+
+ key := c.resolver.cacheKey(ctx, senderJID, isFromMe)
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if value, ok := c.values[key]; ok {
+ return value
+ }
+ value := c.resolver.Resolve(ctx, senderJID, isFromMe, livePushName)
+ c.values[key] = value
+ return value
+}
diff --git a/src/infrastructure/whatsapp/sender_display_name_test.go b/src/infrastructure/whatsapp/sender_display_name_test.go
new file mode 100644
index 00000000..021f0a84
--- /dev/null
+++ b/src/infrastructure/whatsapp/sender_display_name_test.go
@@ -0,0 +1,282 @@
+package whatsapp
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
+)
+
+type senderDisplayNameContactGetter struct {
+ store.NoopStore
+ contacts map[types.JID]types.ContactInfo
+ err error
+ calls int
+}
+
+func (g *senderDisplayNameContactGetter) GetContact(_ context.Context, jid types.JID) (types.ContactInfo, error) {
+ g.calls++
+ if g.err != nil {
+ return types.ContactInfo{}, g.err
+ }
+ return g.contacts[jid], nil
+}
+
+func TestPreferredContactDisplayName(t *testing.T) {
+ tests := []struct {
+ name string
+ contact types.ContactInfo
+ live string
+ want string
+ }{
+ {
+ name: "saved full name wins",
+ contact: types.ContactInfo{FullName: "Saved Name", PushName: "Stored Push", BusinessName: "Business Name"},
+ live: "Live Push",
+ want: "Saved Name",
+ },
+ {
+ name: "live push name beats stored push name",
+ contact: types.ContactInfo{PushName: "Stored Push", BusinessName: "Business Name"},
+ live: "Live Push",
+ want: "Live Push",
+ },
+ {
+ name: "stored push name beats business name",
+ contact: types.ContactInfo{PushName: "Stored Push", BusinessName: "Business Name"},
+ want: "Stored Push",
+ },
+ {
+ name: "business name is the final contact candidate",
+ contact: types.ContactInfo{BusinessName: "Business Name"},
+ want: "Business Name",
+ },
+ {
+ name: "whitespace candidates are skipped without trimming the chosen name",
+ contact: types.ContactInfo{FullName: " \t", PushName: " Stored Push ", BusinessName: "Business Name"},
+ live: " \n",
+ want: " Stored Push ",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := PreferredContactDisplayName(tt.contact, tt.live); got != tt.want {
+ t.Fatalf("PreferredContactDisplayName() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestSenderDisplayNameResolver(t *testing.T) {
+ ctx := context.Background()
+ account := types.NewJID("628111111111", types.DefaultUserServer)
+ other := types.NewJID("628222222222", types.DefaultUserServer)
+
+ tests := []struct {
+ name string
+ getter contactInfoGetter
+ sender string
+ isFromMe bool
+ livePush string
+ deviceName string
+ want string
+ }{
+ {
+ name: "saved full name",
+ getter: &senderDisplayNameContactGetter{contacts: map[types.JID]types.ContactInfo{
+ other: {Found: true, FullName: "Saved Name", PushName: "Stored Push", BusinessName: "Business Name"},
+ }},
+ sender: other.String(),
+ livePush: "Live Push",
+ want: "Saved Name",
+ },
+ {
+ name: "live push name",
+ getter: &senderDisplayNameContactGetter{contacts: map[types.JID]types.ContactInfo{
+ other: {Found: true, PushName: "Stored Push"},
+ }},
+ sender: other.String(),
+ livePush: "Live Push",
+ want: "Live Push",
+ },
+ {
+ name: "stored push name",
+ getter: &senderDisplayNameContactGetter{contacts: map[types.JID]types.ContactInfo{
+ other: {Found: true, PushName: "Stored Push"},
+ }},
+ sender: other.String(),
+ want: "Stored Push",
+ },
+ {
+ name: "business name",
+ getter: &senderDisplayNameContactGetter{contacts: map[types.JID]types.ContactInfo{
+ other: {Found: true, BusinessName: "Business Name"},
+ }},
+ sender: other.String(),
+ want: "Business Name",
+ },
+ {
+ name: "normal user identifier fallback",
+ getter: &senderDisplayNameContactGetter{},
+ sender: other.String(),
+ want: "628222222222",
+ },
+ {
+ name: "lid identifier fallback",
+ getter: &senderDisplayNameContactGetter{},
+ sender: "ABCD1234@lid",
+ want: "ABCD1234",
+ },
+ {
+ name: "malformed sender falls back to its full string",
+ getter: &senderDisplayNameContactGetter{},
+ sender: "not-a-jid",
+ want: "not-a-jid",
+ },
+ {
+ name: "supplied device display name wins for active account",
+ getter: &senderDisplayNameContactGetter{contacts: map[types.JID]types.ContactInfo{
+ account: {Found: true, FullName: "Saved Self", PushName: "Stored Self", BusinessName: "Self Business"},
+ }},
+ sender: "628111111111:[email protected]",
+ isFromMe: true,
+ livePush: "Live Push",
+ deviceName: "Configured Device",
+ want: "Configured Device",
+ },
+ {
+ name: "active account ignores contact and live push names before identifier fallback",
+ getter: &senderDisplayNameContactGetter{contacts: map[types.JID]types.ContactInfo{
+ account: {Found: true, FullName: "Saved Self", PushName: "Stored Self", BusinessName: "Self Business"},
+ }},
+ sender: account.String(),
+ livePush: "Live Push",
+ want: "628111111111",
+ },
+ {
+ name: "active account falls back to account identifier",
+ getter: &senderDisplayNameContactGetter{},
+ sender: account.String(),
+ want: "628111111111",
+ },
+ {
+ name: "contact lookup error falls back to identifier",
+ getter: &senderDisplayNameContactGetter{err: errors.New("contact lookup failed")},
+ sender: other.String(),
+ want: "628222222222",
+ },
+ {
+ name: "nil contact lookup falls back to identifier",
+ sender: other.String(),
+ want: "628222222222",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ resolver := newSenderDisplayNameResolver(tt.getter, nil, account, tt.deviceName)
+ if got := resolver.Resolve(ctx, tt.sender, tt.isFromMe, tt.livePush); got != tt.want {
+ t.Fatalf("Resolve(%q, %t, %q) = %q, want %q", tt.sender, tt.isFromMe, tt.livePush, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestNewSenderDisplayNameResolverDerivesClientPushNameForActiveAccount(t *testing.T) {
+ ctx := context.Background()
+ account := types.NewJID("628111111111", types.DefaultUserServer)
+ client := &whatsmeow.Client{Store: &store.Device{ID: &account, PushName: "Client Push"}}
+
+ resolver := NewSenderDisplayNameResolver(client, "")
+ if got := resolver.Resolve(ctx, account.String(), false, "Live Push"); got != "Client Push" {
+ t.Fatalf("Resolve() = %q, want %q", got, "Client Push")
+ }
+
+ resolver = NewSenderDisplayNameResolver(client, "Configured Device")
+ if got := resolver.Resolve(ctx, account.String(), false, "Live Push"); got != "Configured Device" {
+ t.Fatalf("Resolve() = %q, want %q", got, "Configured Device")
+ }
+}
+
+func TestSenderDisplayNameResolverFallsBackToFullAccountJID(t *testing.T) {
+ resolver := newSenderDisplayNameResolver(nil, nil, types.NewJID("", "account.example"), "")
+
+ if got := resolver.Resolve(context.Background(), "[email protected]", true, "Live Push"); got != "account.example" {
+ t.Fatalf("Resolve() = %q, want %q", got, "account.example")
+ }
+}
+
+func TestSenderDisplayNameCache(t *testing.T) {
+ ctx := context.Background()
+ account := types.NewJID("628111111111", types.DefaultUserServer)
+ other := types.NewJID("628222222222", types.DefaultUserServer)
+ getter := &senderDisplayNameContactGetter{contacts: map[types.JID]types.ContactInfo{
+ account: {Found: true, PushName: "My Push"},
+ other: {Found: true, FullName: "Other Person"},
+ }}
+ resolver := newSenderDisplayNameResolver(getter, nil, account, "")
+
+ cache := NewSenderDisplayNameCache(resolver)
+ if got := cache.Resolve(ctx, other.String(), false, ""); got != "Other Person" {
+ t.Fatalf("first other-person Resolve() = %q, want %q", got, "Other Person")
+ }
+ if got := cache.Resolve(ctx, other.String(), false, "Reaction Push"); got != "Other Person" {
+ t.Fatalf("second other-person Resolve() = %q, want %q", got, "Other Person")
+ }
+ if getter.calls != 1 {
+ t.Fatalf("other-person contact lookups = %d, want 1", getter.calls)
+ }
+
+ secondCache := NewSenderDisplayNameCache(resolver)
+ if got := secondCache.Resolve(ctx, other.String(), false, ""); got != "Other Person" {
+ t.Fatalf("second cache Resolve() = %q, want %q", got, "Other Person")
+ }
+ if getter.calls != 2 {
+ t.Fatalf("contact lookups after second cache = %d, want 2", getter.calls)
+ }
+
+ selfCache := NewSenderDisplayNameCache(resolver)
+ if got := selfCache.Resolve(ctx, "628111111111:[email protected]", true, "Live Push"); got != "628111111111" {
+ t.Fatalf("first self Resolve() = %q, want %q", got, "628111111111")
+ }
+ if got := selfCache.Resolve(ctx, account.String(), true, ""); got != "628111111111" {
+ t.Fatalf("second self Resolve() = %q, want %q", got, "628111111111")
+ }
+ if getter.calls != 2 {
+ t.Fatalf("self contact lookups = %d, want 2", getter.calls)
+ }
+}
+
+func TestAddSenderDisplayNameRequiresSingularNonEmptyFrom(t *testing.T) {
+ tests := []struct {
+ name string
+ payload map[string]any
+ }{
+ {
+ name: "missing from",
+ payload: map[string]any{},
+ },
+ {
+ name: "empty from",
+ payload: map[string]any{"from": ""},
+ },
+ {
+ name: "non string from",
+ payload: map[string]any{"from": []string{"[email protected]"}},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ addSenderDisplayName(context.Background(), nil, tt.payload, false, "Live Push")
+
+ if _, ok := tt.payload["sender_display_name"]; ok {
+ t.Fatalf("sender_display_name unexpectedly added to payload %#v", tt.payload)
+ }
+ })
+ }
+}
diff --git a/src/usecase/chat.go b/src/usecase/chat.go
index 02144c72..b1d8cb70 100644
--- a/src/usecase/chat.go
+++ b/src/usecase/chat.go
@@ -207,31 +207,42 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh
}
// Convert entities to domain objects
+ client := whatsapp.ClientFromContext(ctx)
+ deviceDisplayName := ""
+ if instance, ok := whatsapp.DeviceFromContext(ctx); ok && instance != nil {
+ deviceDisplayName = instance.DisplayName()
+ }
+ senderDisplayNameCache := whatsapp.NewSenderDisplayNameCache(
+ whatsapp.NewSenderDisplayNameResolver(client, deviceDisplayName),
+ )
+
messageInfos := make([]domainChat.MessageInfo, 0, len(messages))
for _, message := range messages {
messageInfo := domainChat.MessageInfo{
- ID: message.ID,
- ChatJID: message.ChatJID,
- SenderJID: message.Sender,
- Content: message.Content,
- Timestamp: message.Timestamp.Format(time.RFC3339),
- IsFromMe: message.IsFromMe,
- MediaType: message.MediaType,
- CallMetadata: message.CallMetadata,
- Filename: message.Filename,
- URL: message.URL,
- FileLength: message.FileLength,
- CreatedAt: message.CreatedAt.Format(time.RFC3339),
- UpdatedAt: message.UpdatedAt.Format(time.RFC3339),
+ ID: message.ID,
+ ChatJID: message.ChatJID,
+ SenderJID: message.Sender,
+ SenderDisplayName: senderDisplayNameCache.Resolve(ctx, message.Sender, message.IsFromMe, ""),
+ Content: message.Content,
+ Timestamp: message.Timestamp.Format(time.RFC3339),
+ IsFromMe: message.IsFromMe,
+ MediaType: message.MediaType,
+ CallMetadata: message.CallMetadata,
+ Filename: message.Filename,
+ URL: message.URL,
+ FileLength: message.FileLength,
+ CreatedAt: message.CreatedAt.Format(time.RFC3339),
+ UpdatedAt: message.UpdatedAt.Format(time.RFC3339),
}
if len(message.Reactions) > 0 {
messageInfo.Reactions = make([]domainChat.ReactionInfo, 0, len(message.Reactions))
for _, reaction := range message.Reactions {
messageInfo.Reactions = append(messageInfo.Reactions, domainChat.ReactionInfo{
- Emoji: reaction.Emoji,
- SenderJID: reaction.ReactorJID,
- IsFromMe: reaction.IsFromMe,
- Timestamp: reaction.Timestamp.Format(time.RFC3339),
+ Emoji: reaction.Emoji,
+ SenderJID: reaction.ReactorJID,
+ SenderDisplayName: senderDisplayNameCache.Resolve(ctx, reaction.ReactorJID, reaction.IsFromMe, ""),
+ IsFromMe: reaction.IsFromMe,
+ Timestamp: reaction.Timestamp.Format(time.RFC3339),
})
}
}
diff --git a/src/usecase/chat_test.go b/src/usecase/chat_test.go
index 074c0356..25292a89 100644
--- a/src/usecase/chat_test.go
+++ b/src/usecase/chat_test.go
@@ -2,17 +2,22 @@ package usecase
import (
"context"
+ "encoding/json"
"testing"
"time"
domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
)
func TestGetChatMessagesMapsReactions(t *testing.T) {
- deviceID := "[email protected]"
+ accountJID := types.NewJID("628999999999", types.DefaultUserServer)
+ deviceID := accountJID.String()
chatJID := "[email protected]"
now := time.Date(2026, time.May, 16, 8, 0, 0, 0, time.UTC)
repo := &chatUsecaseRepoStub{
@@ -46,10 +51,54 @@ func TestGetChatMessagesMapsReactions(t *testing.T) {
},
},
},
+ {
+ ID: "msg-2",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ Sender: accountJID.String(),
+ Content: "reply",
+ IsFromMe: true,
+ Timestamp: now.Add(2 * time.Minute),
+ CreatedAt: now.Add(2 * time.Minute),
+ UpdatedAt: now.Add(2 * time.Minute),
+ Reactions: []domainChatStorage.Reaction{
+ {
+ MessageID: "msg-2",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ ReactorJID: "[email protected]",
+ Emoji: "\U0001f44d",
+ IsFromMe: false,
+ Timestamp: now.Add(3 * time.Minute),
+ },
+ },
+ },
+ {
+ ID: "msg-3",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ Sender: "[email protected]",
+ Content: "again",
+ Timestamp: now.Add(4 * time.Minute),
+ CreatedAt: now.Add(4 * time.Minute),
+ UpdatedAt: now.Add(4 * time.Minute),
+ Reactions: []domainChatStorage.Reaction{
+ {
+ MessageID: "msg-3",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ ReactorJID: accountJID.String(),
+ Emoji: "\U0001f389",
+ IsFromMe: true,
+ Timestamp: now.Add(5 * time.Minute),
+ },
+ },
+ },
},
}
service := NewChatService(repo)
- ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, nil))
+ client := &whatsmeow.Client{Store: &store.Device{ID: &accountJID, PushName: "Primary Account"}}
+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, client, nil))
response, err := service.GetChatMessages(ctx, domainChat.GetChatMessagesRequest{
ChatJID: chatJID,
@@ -58,10 +107,24 @@ func TestGetChatMessagesMapsReactions(t *testing.T) {
if err != nil {
t.Fatalf("get chat messages: %v", err)
}
- if len(response.Data) != 1 {
- t.Fatalf("expected one message, got %d", len(response.Data))
+ if len(response.Data) != 3 {
+ t.Fatalf("expected three messages, got %d", len(response.Data))
+ }
+ firstMessage := response.Data[0]
+ if firstMessage.SenderJID != "[email protected]" {
+ t.Fatalf("expected inbound sender JID to be mapped, got %q", firstMessage.SenderJID)
+ }
+ if firstMessage.SenderDisplayName != "628123456789" {
+ t.Fatalf("expected inbound sender display name, got %q", firstMessage.SenderDisplayName)
}
- reactions := response.Data[0].Reactions
+ if firstMessage.IsFromMe {
+ t.Fatal("expected inbound message is_from_me to be mapped")
+ }
+ if firstMessage.Timestamp != now.Format(time.RFC3339) {
+ t.Fatalf("expected inbound timestamp to be mapped, got %q", firstMessage.Timestamp)
+ }
+
+ reactions := firstMessage.Reactions
if len(reactions) != 1 {
t.Fatalf("expected one reaction, got %d", len(reactions))
}
@@ -71,9 +134,195 @@ func TestGetChatMessagesMapsReactions(t *testing.T) {
if reactions[0].SenderJID != "[email protected]" {
t.Fatalf("expected reactor JID to be mapped, got %q", reactions[0].SenderJID)
}
+ if reactions[0].SenderDisplayName != "628111111111" {
+ t.Fatalf("expected reactor display name, got %q", reactions[0].SenderDisplayName)
+ }
+ if reactions[0].IsFromMe {
+ t.Fatal("expected inbound reaction is_from_me to be mapped")
+ }
if reactions[0].Timestamp != now.Add(time.Minute).Format(time.RFC3339) {
t.Fatalf("expected reaction timestamp to be mapped, got %q", reactions[0].Timestamp)
}
+
+ secondMessage := response.Data[1]
+ if secondMessage.SenderJID != accountJID.String() {
+ t.Fatalf("expected outbound sender JID to be mapped, got %q", secondMessage.SenderJID)
+ }
+ if secondMessage.SenderDisplayName != "Primary Account" {
+ t.Fatalf("expected outbound sender display name, got %q", secondMessage.SenderDisplayName)
+ }
+ if !secondMessage.IsFromMe {
+ t.Fatal("expected outbound message is_from_me to be mapped")
+ }
+ if secondMessage.Timestamp != now.Add(2*time.Minute).Format(time.RFC3339) {
+ t.Fatalf("expected outbound timestamp to be mapped, got %q", secondMessage.Timestamp)
+ }
+ if len(secondMessage.Reactions) != 1 {
+ t.Fatalf("expected one repeated reaction, got %d", len(secondMessage.Reactions))
+ }
+ if secondMessage.Reactions[0].SenderJID != "[email protected]" {
+ t.Fatalf("expected repeated reactor JID to be mapped, got %q", secondMessage.Reactions[0].SenderJID)
+ }
+ if secondMessage.Reactions[0].SenderDisplayName != "628111111111" {
+ t.Fatalf("expected repeated reactor display name, got %q", secondMessage.Reactions[0].SenderDisplayName)
+ }
+ if secondMessage.Reactions[0].Emoji != "\U0001f44d" || secondMessage.Reactions[0].IsFromMe || secondMessage.Reactions[0].Timestamp != now.Add(3*time.Minute).Format(time.RFC3339) {
+ t.Fatalf("expected repeated reaction fields to be mapped, got %#v", secondMessage.Reactions[0])
+ }
+
+ thirdMessage := response.Data[2]
+ if thirdMessage.SenderJID != "[email protected]" || thirdMessage.SenderDisplayName != "628123456789" || thirdMessage.IsFromMe || thirdMessage.Timestamp != now.Add(4*time.Minute).Format(time.RFC3339) {
+ t.Fatalf("expected repeated inbound message fields to be mapped, got %#v", thirdMessage)
+ }
+ if len(thirdMessage.Reactions) != 1 {
+ t.Fatalf("expected one outbound reaction, got %d", len(thirdMessage.Reactions))
+ }
+ if thirdMessage.Reactions[0].SenderJID != accountJID.String() || thirdMessage.Reactions[0].SenderDisplayName != "Primary Account" || !thirdMessage.Reactions[0].IsFromMe || thirdMessage.Reactions[0].Emoji != "\U0001f389" || thirdMessage.Reactions[0].Timestamp != now.Add(5*time.Minute).Format(time.RFC3339) {
+ t.Fatalf("expected outbound reaction fields to be mapped, got %#v", thirdMessage.Reactions[0])
+ }
+}
+
+func TestGetChatMessagesScopesSenderDisplayNameCacheToOneResponse(t *testing.T) {
+ accountJID := types.NewJID("628999999999", types.DefaultUserServer)
+ senderJID := types.NewJID("628123456789", types.DefaultUserServer)
+ deviceID := accountJID.String()
+ chatJID := "[email protected]"
+ now := time.Date(2026, time.July, 28, 10, 0, 0, 0, time.UTC)
+ contacts := &countingContactStore{
+ contacts: map[types.JID]types.ContactInfo{
+ senderJID: {
+ Found: true,
+ FullName: "Saved Participant",
+ },
+ },
+ }
+ repo := &chatUsecaseRepoStub{
+ chat: &domainChatStorage.Chat{
+ DeviceID: deviceID,
+ JID: chatJID,
+ Name: "Study Group",
+ LastMessageTime: now,
+ CreatedAt: now,
+ UpdatedAt: now,
+ },
+ messages: []*domainChatStorage.Message{
+ {
+ ID: "msg-1",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ Sender: senderJID.String(),
+ Content: "hello",
+ Timestamp: now,
+ CreatedAt: now,
+ UpdatedAt: now,
+ Reactions: []domainChatStorage.Reaction{
+ {
+ MessageID: "msg-1",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ ReactorJID: senderJID.String(),
+ Emoji: "\U0001f44d",
+ Timestamp: now.Add(time.Minute),
+ },
+ },
+ },
+ {
+ ID: "msg-2",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ Sender: senderJID.String(),
+ Content: "again",
+ Timestamp: now.Add(2 * time.Minute),
+ CreatedAt: now.Add(2 * time.Minute),
+ UpdatedAt: now.Add(2 * time.Minute),
+ },
+ },
+ }
+ client := &whatsmeow.Client{
+ Store: &store.Device{
+ ID: &accountJID,
+ PushName: "Primary Account",
+ Contacts: contacts,
+ },
+ }
+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, client, nil))
+ service := NewChatService(repo)
+ request := domainChat.GetChatMessagesRequest{
+ ChatJID: chatJID,
+ Limit: 50,
+ }
+
+ firstResponse, err := service.GetChatMessages(ctx, request)
+ if err != nil {
+ t.Fatalf("first GetChatMessages: %v", err)
+ }
+ if len(firstResponse.Data) != 2 || len(firstResponse.Data[0].Reactions) != 1 {
+ t.Fatalf("first response messages/reactions = %#v", firstResponse.Data)
+ }
+ if firstResponse.Data[0].SenderDisplayName != "Saved Participant" ||
+ firstResponse.Data[0].Reactions[0].SenderDisplayName != "Saved Participant" ||
+ firstResponse.Data[1].SenderDisplayName != "Saved Participant" {
+ t.Fatalf("first response sender display names = %#v", firstResponse.Data)
+ }
+ if contacts.reads != 1 {
+ t.Fatalf("contact reads after first response = %d, want 1", contacts.reads)
+ }
+
+ secondResponse, err := service.GetChatMessages(ctx, request)
+ if err != nil {
+ t.Fatalf("second GetChatMessages: %v", err)
+ }
+ if len(secondResponse.Data) != 2 || len(secondResponse.Data[0].Reactions) != 1 {
+ t.Fatalf("second response messages/reactions = %#v", secondResponse.Data)
+ }
+ if secondResponse.Data[0].SenderDisplayName != "Saved Participant" ||
+ secondResponse.Data[0].Reactions[0].SenderDisplayName != "Saved Participant" ||
+ secondResponse.Data[1].SenderDisplayName != "Saved Participant" {
+ t.Fatalf("second response sender display names = %#v", secondResponse.Data)
+ }
+ if contacts.reads != 2 {
+ t.Fatalf("contact reads after second response = %d, want 2", contacts.reads)
+ }
+}
+
+func TestChatSenderDisplayNameJSONContract(t *testing.T) {
+ payload, err := json.Marshal(domainChat.MessageInfo{
+ SenderJID: "[email protected]",
+ SenderDisplayName: "Alice",
+ Reactions: []domainChat.ReactionInfo{{
+ Emoji: "\U0001f44d",
+ SenderJID: "[email protected]",
+ SenderDisplayName: "Bob",
+ }},
+ })
+ if err != nil {
+ t.Fatalf("marshal message payload: %v", err)
+ }
+
+ var message map[string]any
+ if err := json.Unmarshal(payload, &message); err != nil {
+ t.Fatalf("unmarshal message payload: %v", err)
+ }
+ if message["sender_jid"] != "[email protected]" {
+ t.Fatalf("message sender_jid = %#v", message["sender_jid"])
+ }
+ if message["sender_display_name"] != "Alice" {
+ t.Fatalf("message sender_display_name = %#v", message["sender_display_name"])
+ }
+ reactions, ok := message["reactions"].([]any)
+ if !ok || len(reactions) != 1 {
+ t.Fatalf("message reactions = %#v", message["reactions"])
+ }
+ reaction, ok := reactions[0].(map[string]any)
+ if !ok {
+ t.Fatalf("reaction payload = %#v", reactions[0])
+ }
+ if reaction["sender_jid"] != "[email protected]" {
+ t.Fatalf("reaction sender_jid = %#v", reaction["sender_jid"])
+ }
+ if reaction["sender_display_name"] != "Bob" {
+ t.Fatalf("reaction sender_display_name = %#v", reaction["sender_display_name"])
+ }
}
type chatUsecaseRepoStub struct {
diff --git a/src/usecase/group.go b/src/usecase/group.go
index ad33ceb6..78bd1622 100644
--- a/src/usecase/group.go
+++ b/src/usecase/group.go
@@ -598,16 +598,7 @@ func contactDisplayName(ctx context.Context, client *whatsmeow.Client, jid types
}
func contactInfoDisplayName(contact types.ContactInfo) string {
- switch {
- case contact.FullName != "":
- return contact.FullName
- case contact.PushName != "":
- return contact.PushName
- case contact.BusinessName != "":
- return contact.BusinessName
- default:
- return ""
- }
+ return whatsapp.PreferredContactDisplayName(contact, "")
}
func verifiedNameFromUserInfo(info types.UserInfo) string {
diff --git a/src/usecase/group_test.go b/src/usecase/group_test.go
new file mode 100644
index 00000000..0a57bcad
--- /dev/null
+++ b/src/usecase/group_test.go
@@ -0,0 +1,91 @@
+package usecase
+
+import (
+ "context"
+ "testing"
+
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/proto/waVnameCert"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
+)
+
+type countingContactStore struct {
+ store.NoopStore
+ contacts map[types.JID]types.ContactInfo
+ reads int
+}
+
+func (s *countingContactStore) GetContact(_ context.Context, jid types.JID) (types.ContactInfo, error) {
+ s.reads++
+ return s.contacts[jid], nil
+}
+
+func TestResolveParticipantDisplayNamePreservesSourceOrdering(t *testing.T) {
+ participantJID := types.NewJID("628123456789", types.DefaultUserServer)
+ verifiedName := "Verified Business"
+ userInfo := map[types.JID]types.UserInfo{
+ participantJID: {
+ VerifiedName: &types.VerifiedName{
+ Details: &waVnameCert.VerifiedNameCertificate_Details{
+ VerifiedName: &verifiedName,
+ },
+ },
+ },
+ }
+
+ tests := []struct {
+ name string
+ seed string
+ contact types.ContactInfo
+ want string
+ wantReads int
+ }{
+ {
+ name: "seed wins before contact and verified name",
+ seed: "Participant Seed",
+ contact: types.ContactInfo{Found: true, FullName: "Saved Contact"},
+ want: "Participant Seed",
+ wantReads: 0,
+ },
+ {
+ name: "contact wins before verified name",
+ contact: types.ContactInfo{Found: true, FullName: "Saved Contact"},
+ want: "Saved Contact",
+ wantReads: 1,
+ },
+ {
+ name: "verified name follows an unavailable contact",
+ want: "Verified Business",
+ wantReads: 1,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ contacts := &countingContactStore{
+ contacts: map[types.JID]types.ContactInfo{
+ participantJID: tt.contact,
+ },
+ }
+ client := &whatsmeow.Client{
+ Store: &store.Device{Contacts: contacts},
+ }
+
+ got := resolveParticipantDisplayName(
+ context.Background(),
+ client,
+ tt.seed,
+ participantJID,
+ participantJID,
+ userInfo,
+ )
+ if got != tt.want {
+ t.Fatalf("resolveParticipantDisplayName() = %q, want %q", got, tt.want)
+ }
+ if contacts.reads != tt.wantReads {
+ t.Fatalf("contact reads = %d, want %d", contacts.reads, tt.wantReads)
+ }
+ })
+ }
+}