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.

fix(chat): resolve display names from synced contacts (#812)

Aldino Kemalc8455b17d5f6
diff --git a/src/infrastructure/whatsapp/chat_display_name.go b/src/infrastructure/whatsapp/chat_display_name.go
new file mode 100644
index 00000000..49b80dd3
--- /dev/null
+++ b/src/infrastructure/whatsapp/chat_display_name.go
@@ -0,0 +1,187 @@
+package whatsapp
+
+import (
+ "context"
+ "strings"
+
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/types"
+)
+
+// chatContactInfoGetter is the subset of the WhatsApp contact store needed to
+// resolve chat labels. GetContact keeps single-chat requests cheap, while
+// GetAllContacts lets list requests collapse repeated lookups into one snapshot.
+type chatContactInfoGetter interface {
+ GetContact(context.Context, types.JID) (types.ContactInfo, error)
+ GetAllContacts(context.Context) (map[types.JID]types.ContactInfo, error)
+}
+
+// ChatDisplayNameResolver resolves a human-readable chat label from the chat
+// metadata already stored by GOWA and the address book synced by whatsmeow.
+// It starts with point lookups, then switches to a contact snapshot when a
+// second distinct contact is needed. This keeps chat detail requests O(1)
+// without turning chat lists into N+1 database reads.
+type ChatDisplayNameResolver struct {
+ client *whatsmeow.Client
+ contacts chatContactInfoGetter
+ contactCache map[types.JID]types.ContactInfo
+ allContacts map[types.JID]types.ContactInfo
+ pointLookups int
+ bulkAttempted bool
+}
+
+// NewChatDisplayNameResolver builds a resolver scoped to one response. Contact
+// store failures are deliberately non-fatal: callers still receive the existing
+// deterministic JID-derived fallback instead of failing the chat API.
+func NewChatDisplayNameResolver(_ context.Context, client *whatsmeow.Client) *ChatDisplayNameResolver {
+ var contacts chatContactInfoGetter
+ if client != nil && client.Store != nil {
+ contacts = client.Store.Contacts
+ }
+ return newChatDisplayNameResolver(contacts, client)
+}
+
+func newChatDisplayNameResolver(contacts chatContactInfoGetter, client *whatsmeow.Client) *ChatDisplayNameResolver {
+ return &ChatDisplayNameResolver{
+ client: client,
+ contacts: contacts,
+ contactCache: make(map[types.JID]types.ContactInfo),
+ }
+}
+
+// Resolve applies the shared chat display-name policy:
+// - preserve meaningful stored chat names (group subjects, newsletter names,
+// or another explicit label),
+// - for empty/number/JID placeholders use synced FullName,
+// - then synced PushName and BusinessName,
+// - finally use the JID-derived label.
+//
+// status@broadcast, groups, and newsletters retain their existing GOWA fallback
+// semantics. LID identifiers are normalized through the active device mapping
+// before contact lookup when possible.
+func (r *ChatDisplayNameResolver) Resolve(ctx context.Context, rawJID, storedName string) string {
+ if rawJID == "status@broadcast" {
+ return "Status"
+ }
+
+ originalJID, originalValid := parseChatJID(rawJID)
+ jid, validJID := r.normalizeJID(ctx, rawJID)
+ if validJID {
+ switch jid.Server {
+ case types.GroupServer:
+ if hasDisplayName(storedName) {
+ return storedName
+ }
+ return "Group " + jid.User
+ case types.NewsletterServer:
+ if hasDisplayName(storedName) {
+ return storedName
+ }
+ return "Newsletter " + jid.User
+ }
+ }
+
+ if hasDisplayName(storedName) && !isJIDFallbackName(rawJID, originalJID, originalValid, jid, validJID, storedName) {
+ return storedName
+ }
+
+ if validJID {
+ if contact, ok := r.contactInfo(ctx, jid); ok {
+ if name := PreferredContactDisplayName(contact, ""); name != "" {
+ return name
+ }
+ }
+ if hasDisplayName(jid.User) {
+ return jid.User
+ }
+ }
+
+ if hasDisplayName(storedName) {
+ return storedName
+ }
+ return rawJID
+}
+
+func parseChatJID(rawJID string) (types.JID, bool) {
+ jid, err := types.ParseJID(rawJID)
+ if err != nil || jid.IsEmpty() || !hasDisplayName(jid.User) {
+ return types.EmptyJID, false
+ }
+ return jid.ToNonAD(), true
+}
+
+func (r *ChatDisplayNameResolver) normalizeJID(ctx context.Context, rawJID string) (types.JID, bool) {
+ jid, valid := parseChatJID(rawJID)
+ if !valid {
+ return types.EmptyJID, false
+ }
+ if jid.Server == types.HiddenUserServer && r != nil && 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 *ChatDisplayNameResolver) contactInfo(ctx context.Context, jid types.JID) (types.ContactInfo, bool) {
+ if r == nil || r.contacts == nil {
+ return types.ContactInfo{}, false
+ }
+ jid = jid.ToNonAD()
+
+ if contact, ok := r.contactCache[jid]; ok {
+ return contact, usableContactInfo(contact)
+ }
+ if r.allContacts != nil {
+ contact, ok := r.allContacts[jid]
+ if !ok {
+ r.contactCache[jid] = types.ContactInfo{}
+ return types.ContactInfo{}, false
+ }
+ r.contactCache[jid] = contact
+ return contact, usableContactInfo(contact)
+ }
+
+ // A single chat detail only needs one point lookup. When a response asks for
+ // another distinct contact (typical for chat lists), switch to one bulk read
+ // and serve the rest from memory.
+ if r.pointLookups > 0 && !r.bulkAttempted {
+ r.bulkAttempted = true
+ if allContacts, err := r.contacts.GetAllContacts(ctx); err == nil {
+ r.allContacts = allContacts
+ if contact, ok := allContacts[jid]; ok {
+ r.contactCache[jid] = contact
+ return contact, usableContactInfo(contact)
+ }
+ r.contactCache[jid] = types.ContactInfo{}
+ return types.ContactInfo{}, false
+ }
+ }
+
+ contact, err := r.contacts.GetContact(ctx, jid)
+ r.pointLookups++
+ if err != nil {
+ return types.ContactInfo{}, false
+ }
+ r.contactCache[jid] = contact
+ return contact, usableContactInfo(contact)
+}
+
+func usableContactInfo(contact types.ContactInfo) bool {
+ return contact.Found || hasDisplayName(contact.FullName) || hasDisplayName(contact.PushName) || hasDisplayName(contact.BusinessName)
+}
+
+func isJIDFallbackName(rawJID string, originalJID types.JID, originalValid bool, normalizedJID types.JID, normalizedValid bool, storedName string) bool {
+ name := strings.TrimSpace(storedName)
+ if name == "" || name == strings.TrimSpace(rawJID) {
+ return true
+ }
+ if originalValid && (name == originalJID.User || name == originalJID.String()) {
+ return true
+ }
+ if normalizedValid && (name == normalizedJID.User || name == normalizedJID.String()) {
+ return true
+ }
+ return false
+}
diff --git a/src/infrastructure/whatsapp/chat_display_name_test.go b/src/infrastructure/whatsapp/chat_display_name_test.go
new file mode 100644
index 00000000..74bf80dd
--- /dev/null
+++ b/src/infrastructure/whatsapp/chat_display_name_test.go
@@ -0,0 +1,211 @@
+package whatsapp
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
+ waLog "go.mau.fi/whatsmeow/util/log"
+)
+
+type chatDisplayNameContactStore struct {
+ contacts map[types.JID]types.ContactInfo
+ getErr error
+ allErr error
+ getReads int
+ bulkReads int
+}
+
+func (s *chatDisplayNameContactStore) GetContact(_ context.Context, jid types.JID) (types.ContactInfo, error) {
+ s.getReads++
+ if s.getErr != nil {
+ return types.ContactInfo{}, s.getErr
+ }
+ contact, ok := s.contacts[jid.ToNonAD()]
+ if !ok {
+ return types.ContactInfo{}, nil
+ }
+ return contact, nil
+}
+
+func (s *chatDisplayNameContactStore) GetAllContacts(context.Context) (map[types.JID]types.ContactInfo, error) {
+ s.bulkReads++
+ return s.contacts, s.allErr
+}
+
+type chatDisplayNameLIDStore struct {
+ lid types.JID
+ pn types.JID
+}
+
+func (s *chatDisplayNameLIDStore) PutManyLIDMappings(context.Context, []store.LIDMapping) error {
+ return nil
+}
+
+func (s *chatDisplayNameLIDStore) PutLIDMapping(context.Context, types.JID, types.JID) error {
+ return nil
+}
+
+func (s *chatDisplayNameLIDStore) GetPNForLID(_ context.Context, lid types.JID) (types.JID, error) {
+ if lid.ToNonAD() == s.lid.ToNonAD() {
+ return s.pn, nil
+ }
+ return types.EmptyJID, nil
+}
+
+func (s *chatDisplayNameLIDStore) GetLIDForPN(_ context.Context, pn types.JID) (types.JID, error) {
+ if pn.ToNonAD() == s.pn.ToNonAD() {
+ return s.lid, nil
+ }
+ return types.EmptyJID, nil
+}
+
+func (s *chatDisplayNameLIDStore) GetManyLIDsForPNs(_ context.Context, pns []types.JID) (map[types.JID]types.JID, error) {
+ result := make(map[types.JID]types.JID)
+ for _, pn := range pns {
+ if pn.ToNonAD() == s.pn.ToNonAD() {
+ result[pn.ToNonAD()] = s.lid.ToNonAD()
+ }
+ }
+ return result, nil
+}
+
+func TestChatDisplayNameResolverUsesSyncedContactForFallbackChatName(t *testing.T) {
+ ctx := context.Background()
+ jid := types.NewJID("628123456789", types.DefaultUserServer)
+ contacts := &chatDisplayNameContactStore{contacts: map[types.JID]types.ContactInfo{
+ jid: {
+ Found: true,
+ FullName: "Saved Alice",
+ PushName: "Alice WA",
+ BusinessName: "Alice Shop",
+ },
+ }}
+ resolver := newChatDisplayNameResolver(contacts, nil)
+
+ for _, storedName := range []string{"", jid.User, jid.String()} {
+ if got := resolver.Resolve(ctx, jid.String(), storedName); got != "Saved Alice" {
+ t.Fatalf("Resolve(%q, %q) = %q, want synced full name", jid.String(), storedName, got)
+ }
+ }
+ if contacts.getReads != 1 {
+ t.Fatalf("GetContact reads = %d, want 1 cached point lookup", contacts.getReads)
+ }
+ if contacts.bulkReads != 0 {
+ t.Fatalf("GetAllContacts reads = %d, want 0 for one chat", contacts.bulkReads)
+ }
+}
+
+func TestChatDisplayNameResolverResolvesLateLIDPlaceholderThroughPNContact(t *testing.T) {
+ originalLog := log
+ log = waLog.Noop
+ defer func() { log = originalLog }()
+
+ ctx := context.Background()
+ lid := types.NewJID("123456789012345", types.HiddenUserServer)
+ pn := types.NewJID("628123456789", types.DefaultUserServer)
+ contacts := &chatDisplayNameContactStore{contacts: map[types.JID]types.ContactInfo{
+ pn: {Found: true, FullName: "Saved Alice"},
+ }}
+ client := &whatsmeow.Client{Store: &store.Device{
+ LIDs: &chatDisplayNameLIDStore{lid: lid, pn: pn},
+ }}
+ resolver := newChatDisplayNameResolver(contacts, client)
+
+ // The chat was persisted before LID->PN mapping existed, so its stored name
+ // is the old LID user placeholder. Once the mapping appears, that placeholder
+ // must not outrank the synced PN contact name.
+ if got := resolver.Resolve(ctx, lid.String(), lid.User); got != "Saved Alice" {
+ t.Fatalf("Resolve(%q, %q) = %q, want synced PN contact name", lid.String(), lid.User, got)
+ }
+ if contacts.getReads != 1 {
+ t.Fatalf("GetContact reads = %d, want one PN contact lookup", contacts.getReads)
+ }
+}
+
+func TestChatDisplayNameResolverPreservesMeaningfulStoredName(t *testing.T) {
+ ctx := context.Background()
+ jid := types.NewJID("628123456789", types.DefaultUserServer)
+ contacts := &chatDisplayNameContactStore{contacts: map[types.JID]types.ContactInfo{
+ jid: {Found: true, FullName: "Saved Alice"},
+ }}
+ resolver := newChatDisplayNameResolver(contacts, nil)
+
+ if got := resolver.Resolve(ctx, jid.String(), "Support Queue"); got != "Support Queue" {
+ t.Fatalf("Resolve() = %q, want meaningful stored chat name", got)
+ }
+ if contacts.getReads != 0 || contacts.bulkReads != 0 {
+ t.Fatalf("contact store reads = point:%d bulk:%d, want none for meaningful stored name", contacts.getReads, contacts.bulkReads)
+ }
+}
+
+func TestChatDisplayNameResolverUsesContactFallbackOrder(t *testing.T) {
+ ctx := context.Background()
+ pushJID := types.NewJID("628111111111", types.DefaultUserServer)
+ businessJID := types.NewJID("628222222222", types.DefaultUserServer)
+ phoneJID := types.NewJID("628333333333", types.DefaultUserServer)
+ contacts := &chatDisplayNameContactStore{contacts: map[types.JID]types.ContactInfo{
+ pushJID: {Found: true, PushName: "Push Alice", BusinessName: "Alice Shop"},
+ businessJID: {Found: true, BusinessName: "Business Bob"},
+ }}
+ resolver := newChatDisplayNameResolver(contacts, nil)
+
+ cases := []struct {
+ name string
+ jid types.JID
+ want string
+ }{
+ {name: "push name", jid: pushJID, want: "Push Alice"},
+ {name: "business name", jid: businessJID, want: "Business Bob"},
+ {name: "phone number", jid: phoneJID, want: phoneJID.User},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := resolver.Resolve(ctx, tc.jid.String(), tc.jid.User); got != tc.want {
+ t.Fatalf("Resolve() = %q, want %q", got, tc.want)
+ }
+ })
+ }
+ if contacts.getReads != 1 || contacts.bulkReads != 1 {
+ t.Fatalf("contact store reads = point:%d bulk:%d, want one point then one bulk read", contacts.getReads, contacts.bulkReads)
+ }
+}
+
+func TestChatDisplayNameResolverKeepsSpecialChatSemantics(t *testing.T) {
+ ctx := context.Background()
+ contacts := &chatDisplayNameContactStore{}
+ resolver := newChatDisplayNameResolver(contacts, nil)
+
+ cases := []struct {
+ jid string
+ storedName string
+ want string
+ }{
+ {jid: "status@broadcast", want: "Status"},
+ {jid: "[email protected]", storedName: "Family", want: "Family"},
+ {jid: "[email protected]", want: "Group 120363999000111"},
+ {jid: "120363111@newsletter", storedName: "Updates", want: "Updates"},
+ {jid: "120363111@newsletter", want: "Newsletter 120363111"},
+ }
+ for _, tc := range cases {
+ if got := resolver.Resolve(ctx, tc.jid, tc.storedName); got != tc.want {
+ t.Fatalf("Resolve(%q, %q) = %q, want %q", tc.jid, tc.storedName, got, tc.want)
+ }
+ }
+ if contacts.getReads != 0 || contacts.bulkReads != 0 {
+ t.Fatalf("contact store reads = point:%d bulk:%d, want none for special chats", contacts.getReads, contacts.bulkReads)
+ }
+}
+
+func TestChatDisplayNameResolverContactReadFailureDoesNotBreakChats(t *testing.T) {
+ ctx := context.Background()
+ jid := types.NewJID("628123456789", types.DefaultUserServer)
+ resolver := newChatDisplayNameResolver(&chatDisplayNameContactStore{getErr: errors.New("contact store unavailable")}, nil)
+
+ if got := resolver.Resolve(ctx, jid.String(), jid.User); got != jid.User {
+ t.Fatalf("Resolve() = %q, want deterministic phone fallback %q", got, jid.User)
+ }
+}
diff --git a/src/usecase/chat.go b/src/usecase/chat.go
index e532585d..f5753273 100644
--- a/src/usecase/chat.go
+++ b/src/usecase/chat.go
@@ -3,7 +3,6 @@ package usecase
import (
"context"
"fmt"
- "strings"
"time"
domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
@@ -26,38 +25,13 @@ func NewChatService(chatStorageRepo domainChatStorage.IChatStorageRepository) do
}
}
-// chatDisplayName returns a human-readable name for a chat, falling back to a
-// JID-derived label when the stored name is empty. Some chats are persisted
-// before a pushname/group subject is known (or with stale empty names), which
-// otherwise surfaces as a blank "name" in the chat list and makes the sender
-// impossible to identify (issue #675). The fallback mirrors the storage-layer
-// convention in GetChatNameWithPushName: "Status" for status@broadcast, phone
-// number for 1:1, "Group <id>" / "Newsletter <id>" for those address spaces.
-func chatDisplayName(jid, name string) string {
- if name != "" {
- return name
- }
- // Mirror the storage-layer contract (GetChatNameWithPushNameByDevice):
- // status@broadcast is always titled "Status", never its lowercase JID local part.
- if jid == "status@broadcast" {
- return "Status"
- }
- user := utils.ExtractPhoneFromJID(jid)
- switch {
- case utils.IsGroupJID(jid):
- return "Group " + user
- case strings.HasSuffix(jid, "@newsletter"):
- return "Newsletter " + user
- default:
- return user
- }
-}
-
func (service serviceChat) ListChats(ctx context.Context, request domainChat.ListChatsRequest) (response domainChat.ListChatsResponse, err error) {
if err = validations.ValidateListChats(ctx, &request); err != nil {
return response, err
}
+ chatDisplayNameResolver := whatsapp.NewChatDisplayNameResolver(ctx, whatsapp.ClientFromContext(ctx))
+
// Create filter from request
filter := &domainChatStorage.ChatFilter{
DeviceID: deviceIDFromContext(ctx),
@@ -88,7 +62,7 @@ func (service serviceChat) ListChats(ctx context.Context, request domainChat.Lis
for _, chat := range chats {
chatInfo := domainChat.ChatInfo{
JID: chat.JID,
- Name: chatDisplayName(chat.JID, chat.Name),
+ Name: chatDisplayNameResolver.Resolve(ctx, chat.JID, chat.Name),
LastMessageTime: chat.LastMessageTime.Format(time.RFC3339),
EphemeralExpiration: chat.EphemeralExpiration,
CreatedAt: chat.CreatedAt.Format(time.RFC3339),
@@ -127,6 +101,9 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh
return response, fmt.Errorf("device identification required")
}
+ client := whatsapp.ClientFromContext(ctx)
+ chatDisplayNameResolver := whatsapp.NewChatDisplayNameResolver(ctx, client)
+
chat, err := service.chatStorageRepo.GetChatByDevice(deviceID, request.ChatJID)
if err != nil {
logrus.WithError(err).WithField("chat_jid", request.ChatJID).Error("Failed to get chat info")
@@ -148,7 +125,7 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh
}
response.ChatInfo = domainChat.ChatInfo{
JID: request.ChatJID,
- Name: chatDisplayName(request.ChatJID, ""),
+ Name: chatDisplayNameResolver.Resolve(ctx, request.ChatJID, ""),
}
return response, nil
}
@@ -207,7 +184,6 @@ 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()
@@ -252,7 +228,7 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh
// Create chat info for response
chatInfo := domainChat.ChatInfo{
JID: chat.JID,
- Name: chatDisplayName(chat.JID, chat.Name),
+ Name: chatDisplayNameResolver.Resolve(ctx, chat.JID, chat.Name),
LastMessageTime: chat.LastMessageTime.Format(time.RFC3339),
EphemeralExpiration: chat.EphemeralExpiration,
CreatedAt: chat.CreatedAt.Format(time.RFC3339),
diff --git a/src/usecase/chat_display_name_test.go b/src/usecase/chat_display_name_test.go
new file mode 100644
index 00000000..ed63ffb1
--- /dev/null
+++ b/src/usecase/chat_display_name_test.go
@@ -0,0 +1,170 @@
+package usecase
+
+import (
+ "context"
+ "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"
+)
+
+// chatDisplayName keeps the existing table-driven fallback coverage focused on
+// the production resolver after the local helper moved to infrastructure.
+func chatDisplayName(jid, name string) string {
+ ctx := context.Background()
+ return whatsapp.NewChatDisplayNameResolver(ctx, nil).Resolve(ctx, jid, name)
+}
+
+// chatContactStoreStub serves the synced address book that the chat usecases
+// read through the active device's whatsmeow client. Only the two read paths
+// used by the resolver carry behaviour; the writes are unused here.
+type chatContactStoreStub struct {
+ contacts map[types.JID]types.ContactInfo
+}
+
+func (s *chatContactStoreStub) GetContact(_ context.Context, user types.JID) (types.ContactInfo, error) {
+ return s.contacts[user.ToNonAD()], nil
+}
+
+func (s *chatContactStoreStub) GetAllContacts(context.Context) (map[types.JID]types.ContactInfo, error) {
+ return s.contacts, nil
+}
+
+func (s *chatContactStoreStub) PutPushName(context.Context, types.JID, string) (bool, string, error) {
+ return false, "", nil
+}
+
+func (s *chatContactStoreStub) PutBusinessName(context.Context, types.JID, string) (bool, string, error) {
+ return false, "", nil
+}
+
+func (s *chatContactStoreStub) PutContactName(context.Context, types.JID, string, string) error {
+ return nil
+}
+
+func (s *chatContactStoreStub) PutAllContactNames(context.Context, []store.ContactEntry) error {
+ return nil
+}
+
+func (s *chatContactStoreStub) PutManyRedactedPhones(context.Context, []store.RedactedPhoneEntry) error {
+ return nil
+}
+
+// chatDisplayNameContext mirrors how the REST/MCP layers hand the active device
+// to the usecases, so these tests exercise the real ClientFromContext path.
+func chatDisplayNameContext(accountJID types.JID, contacts map[types.JID]types.ContactInfo) context.Context {
+ client := &whatsmeow.Client{Store: &store.Device{
+ ID: &accountJID,
+ Contacts: &chatContactStoreStub{contacts: contacts},
+ }}
+ return whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(accountJID.String(), client, nil))
+}
+
+// TestListChatsResolvesSyncedContactNames pins the ListChats half of issue #805:
+// a stored phone/JID placeholder must be replaced by the synced contact name,
+// while an explicit chat label is still returned verbatim.
+func TestListChatsResolvesSyncedContactNames(t *testing.T) {
+ accountJID := types.NewJID("628999999999", types.DefaultUserServer)
+ alice := types.NewJID("628123456789", types.DefaultUserServer)
+ bob := types.NewJID("628111111111", types.DefaultUserServer)
+ now := time.Date(2026, time.May, 16, 8, 0, 0, 0, time.UTC)
+
+ repo := &chatUsecaseRepoStub{chats: []*domainChatStorage.Chat{
+ {DeviceID: accountJID.String(), JID: alice.String(), Name: alice.User, LastMessageTime: now, CreatedAt: now, UpdatedAt: now},
+ {DeviceID: accountJID.String(), JID: bob.String(), Name: "Support Queue", LastMessageTime: now, CreatedAt: now, UpdatedAt: now},
+ }}
+ ctx := chatDisplayNameContext(accountJID, map[types.JID]types.ContactInfo{
+ alice: {Found: true, FullName: "Saved Alice"},
+ bob: {Found: true, FullName: "Saved Bob"},
+ })
+
+ response, err := NewChatService(repo).ListChats(ctx, domainChat.ListChatsRequest{})
+ if err != nil {
+ t.Fatalf("list chats: %v", err)
+ }
+ if len(response.Data) != 2 {
+ t.Fatalf("expected two chats, got %d", len(response.Data))
+ }
+ if response.Data[0].Name != "Saved Alice" {
+ t.Fatalf("placeholder chat name = %q, want synced contact name", response.Data[0].Name)
+ }
+ if response.Data[1].Name != "Support Queue" {
+ t.Fatalf("explicit chat name = %q, want it preserved", response.Data[1].Name)
+ }
+}
+
+// TestGetChatMessagesResolvesSyncedContactNameForEmptyChat covers the
+// not-yet-persisted chat response, where chat_info has no stored name at all.
+func TestGetChatMessagesResolvesSyncedContactNameForEmptyChat(t *testing.T) {
+ accountJID := types.NewJID("628999999999", types.DefaultUserServer)
+ alice := types.NewJID("628123456789", types.DefaultUserServer)
+
+ ctx := chatDisplayNameContext(accountJID, map[types.JID]types.ContactInfo{
+ alice: {Found: true, FullName: "Saved Alice"},
+ })
+
+ response, err := NewChatService(&chatUsecaseRepoStub{}).GetChatMessages(ctx, domainChat.GetChatMessagesRequest{
+ ChatJID: alice.String(),
+ })
+ if err != nil {
+ t.Fatalf("get chat messages: %v", err)
+ }
+ if len(response.Data) != 0 {
+ t.Fatalf("expected empty message list, got %d", len(response.Data))
+ }
+ if response.ChatInfo.Name != "Saved Alice" {
+ t.Fatalf("empty chat_info name = %q, want synced contact name", response.ChatInfo.Name)
+ }
+}
+
+// TestGetChatMessagesResolvesSyncedContactNameForLoadedChat covers the stored
+// chat response, where chat_info carries a phone-number placeholder.
+func TestGetChatMessagesResolvesSyncedContactNameForLoadedChat(t *testing.T) {
+ accountJID := types.NewJID("628999999999", types.DefaultUserServer)
+ alice := types.NewJID("628123456789", types.DefaultUserServer)
+ now := time.Date(2026, time.May, 16, 8, 0, 0, 0, time.UTC)
+
+ repo := &chatUsecaseRepoStub{
+ chat: &domainChatStorage.Chat{
+ DeviceID: accountJID.String(),
+ JID: alice.String(),
+ Name: alice.User,
+ LastMessageTime: now,
+ CreatedAt: now,
+ UpdatedAt: now,
+ },
+ messages: []*domainChatStorage.Message{
+ {
+ ID: "msg-1",
+ ChatJID: alice.String(),
+ DeviceID: accountJID.String(),
+ Sender: alice.String(),
+ Content: "hi",
+ Timestamp: now,
+ CreatedAt: now,
+ UpdatedAt: now,
+ },
+ },
+ }
+ ctx := chatDisplayNameContext(accountJID, map[types.JID]types.ContactInfo{
+ alice: {Found: true, FullName: "Saved Alice"},
+ })
+
+ response, err := NewChatService(repo).GetChatMessages(ctx, domainChat.GetChatMessagesRequest{
+ ChatJID: alice.String(),
+ })
+ 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 response.ChatInfo.Name != "Saved Alice" {
+ t.Fatalf("loaded chat_info name = %q, want synced contact name", response.ChatInfo.Name)
+ }
+}
diff --git a/src/usecase/chat_test.go b/src/usecase/chat_test.go
index 3ce0cc86..931f4ff5 100644
--- a/src/usecase/chat_test.go
+++ b/src/usecase/chat_test.go
@@ -372,6 +372,7 @@ func TestChatSenderDisplayNameJSONContract(t *testing.T) {
type chatUsecaseRepoStub struct {
domainChatStorage.IChatStorageRepository
chat *domainChatStorage.Chat
+ chats []*domainChatStorage.Chat
messages []*domainChatStorage.Message
globalMessageCount int64
deviceMessageCounts map[string]int64
@@ -381,6 +382,14 @@ func (r *chatUsecaseRepoStub) GetChatByDevice(_, _ string) (*domainChatStorage.C
return r.chat, nil
}
+func (r *chatUsecaseRepoStub) GetChats(*domainChatStorage.ChatFilter) ([]*domainChatStorage.Chat, error) {
+ return r.chats, nil
+}
+
+func (r *chatUsecaseRepoStub) GetFilteredChatCount(*domainChatStorage.ChatFilter) (int64, error) {
+ return int64(len(r.chats)), nil
+}
+
func (r *chatUsecaseRepoStub) GetMessages(*domainChatStorage.MessageFilter) ([]*domainChatStorage.Message, error) {
return r.messages, nil
}