GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
fix(message,send): quoted replies show pre-edit text and an unresolvable participant (#820)
Alen Philip Georgefbc960015b39
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.goindex 2c8d1a2d..39272906 100644--- a/src/infrastructure/chatstorage/sqlite_repository.go+++ b/src/infrastructure/chatstorage/sqlite_repository.go@@ -351,6 +351,82 @@ func (r *SQLiteRepository) StoreMessage(message *domainChatStorage.Message) erro}// StoreMessagesBatch creates or updates multiple messages in a single transaction+// storeSentMessagePreservingEdits writes a sent message without ever moving its+// content backwards.+//+// The edit check lives INSIDE the UPDATE rather than in a preceding SELECT: a+// separate check leaves a window where an edit can commit between the check and+// the write, and the write then clobbers it. SQLite evaluates the EXISTS as part+// of the same statement, so the check and the write are one operation.+//+// Everything except content is written as normal — only content is pinned once+// an edit exists for this row.+func (r *SQLiteRepository) storeSentMessagePreservingEdits(message *domainChatStorage.Message) error {+ now := time.Now()+ message.CreatedAt = now+ message.UpdatedAt = now++ if message.Content == "" && message.MediaType == "" {+ return nil+ }++ const guardedUpdate = `+ UPDATE messages SET sender = ?,+ content = CASE WHEN EXISTS (+ SELECT 1 FROM message_edits+ WHERE original_message_id = messages.id+ AND chat_jid = messages.chat_jid+ AND device_id = messages.device_id+ ) THEN content ELSE ? END,+ timestamp = ?, is_from_me = ?,+ media_type = ?, call_metadata = ?, filename = ?, url = ?, direct_path = ?, media_key = ?, file_sha256 = ?,+ file_enc_sha256 = ?, file_length = ?, referral_metadata = ?, updated_at = ?+ WHERE id = ? AND chat_jid = ? AND device_id = ?+ `+ updateArgs := []any{+ message.Sender, message.Content, message.Timestamp, message.IsFromMe,+ message.MediaType, message.CallMetadata, message.Filename, message.URL, message.DirectPath,+ message.MediaKey, message.FileSHA256, message.FileEncSHA256, message.FileLength,+ message.ReferralMetadata, message.UpdatedAt,+ message.ID, message.ChatJID, message.DeviceID,+ }++ result, err := r.db.Exec(guardedUpdate, updateArgs...)+ if err != nil {+ return err+ }+ if rows, _ := result.RowsAffected(); rows > 0 {+ return nil+ }++ _, insertErr := r.db.Exec(`+ INSERT INTO messages (+ id, chat_jid, device_id, sender, content, timestamp, is_from_me,+ media_type, call_metadata, filename, url, direct_path, media_key, file_sha256,+ file_enc_sha256, file_length, referral_metadata, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `, message.ID, message.ChatJID, message.DeviceID, message.Sender, message.Content,+ message.Timestamp, message.IsFromMe, message.MediaType, message.CallMetadata, message.Filename,+ message.URL, message.DirectPath, message.MediaKey, message.FileSHA256, message.FileEncSHA256,+ message.FileLength, message.ReferralMetadata, message.CreatedAt, message.UpdatedAt)+ if insertErr == nil {+ return nil+ }++ // Lost the insert race: an edit created the row between the update above and+ // this insert. Re-run the guarded update so the sent metadata still lands and+ // the edited content is preserved. Only if that finds nothing is the insert+ // error real.+ retry, retryErr := r.db.Exec(guardedUpdate, updateArgs...)+ if retryErr != nil {+ return insertErr+ }+ if rows, _ := retry.RowsAffected(); rows > 0 {+ return nil+ }+ return insertErr+}+func (r *SQLiteRepository) StoreMessagesBatch(messages []*domainChatStorage.Message) error {if len(messages) == 0 {return nil@@ -2683,7 +2759,12 @@ func (r *SQLiteRepository) StoreSentMessageWithContext(ctx context.Context, messFileEncSHA256: fileEncSHA256,FileLength: fileLength,}- if err := r.StoreMessage(message); err != nil {+ // wrapSendMessage persists asynchronously, so an edit sent moments later can+ // reach storage BEFORE this does. StoreMessage's existing-row path updates+ // content unconditionally, so writing the original text now would roll that+ // edit back — and mergeReplyContext quotes from that row, which is the stale+ // quote the edit sync exists to prevent.+ if err := r.storeSentMessagePreservingEdits(message); err != nil {return fmt.Errorf("failed to store message: %w", err)}diff --git a/src/infrastructure/chatstorage/sqlite_repository_sent_edit_order_test.go b/src/infrastructure/chatstorage/sqlite_repository_sent_edit_order_test.gonew file mode 100644index 00000000..d72546e3--- /dev/null+++ b/src/infrastructure/chatstorage/sqlite_repository_sent_edit_order_test.go@@ -0,0 +1,161 @@+package chatstorage++import (+ "context"+ "sync"+ "testing"+ "time"++ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"+ _ "github.com/mattn/go-sqlite3"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "go.mau.fi/whatsmeow/proto/waCommon"+ "go.mau.fi/whatsmeow/proto/waE2E"+ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+ "google.golang.org/protobuf/proto"+)++// wrapSendMessage persists a sent message from a goroutine, so an edit can reach+// storage before the original write does. These pin the resulting order, without+// depending on the scheduler: the writes are issued in the order the race+// produces, which is what a blocked original store amounts to.++const (+ orderChatJID = "[email protected]"+ orderDevice = "[email protected]"+ orderMsgID = "MSG-ORDER-1"+)++func orderTestRepo(t *testing.T) (*SQLiteRepository, context.Context) {+ t.Helper()+ repo := NewStorageRepository(openTestDB(t)).(*SQLiteRepository)+ require.NoError(t, repo.InitializeSchema())+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(orderDevice, nil, nil))+ return repo, ctx+}++func editEvent(id, newContent string, at time.Time) *events.Message {+ return &events.Message{+ Info: types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: types.NewJID("628123456789", types.DefaultUserServer),+ Sender: types.NewJID("628123456789", types.DefaultUserServer),+ IsFromMe: true,+ },+ ID: "EDIT-EVT-1",+ Timestamp: at,+ },+ Message: &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{+ Type: waE2E.ProtocolMessage_MESSAGE_EDIT.Enum(),+ Key: &waCommon.MessageKey{+ ID: proto.String(id),+ RemoteJID: proto.String(orderChatJID),+ FromMe: proto.Bool(true),+ },+ EditedMessage: &waE2E.Message{Conversation: proto.String(newContent)},+ }},+ }+}++// The race: the edit lands first, then the delayed original store arrives. The+// original content must NOT come back — that is the stale quote all over again.+func TestDelayedSentStoreDoesNotOverwriteAnEarlierEdit(t *testing.T) {+ repo, ctx := orderTestRepo(t)+ now := time.Now().UTC()++ // 1. the edit reaches storage first (original row does not exist yet)+ require.NoError(t, repo.CreateMessage(ctx, editEvent(orderMsgID, "EDITED content", now)))++ // 2. the goroutine from wrapSendMessage finally runs, carrying the ORIGINAL+ require.NoError(t, repo.StoreSentMessageWithContext(+ ctx, orderMsgID, "[email protected]", orderChatJID,+ "ORIGINAL content", now, nil,+ ))++ stored, err := repo.GetMessageByIDAndDevice(orderDevice, orderMsgID)+ require.NoError(t, err)+ require.NotNil(t, stored)+ assert.Equal(t, "EDITED content", stored.Content,+ "the delayed original store rolled the edit back")+}++// The ordinary order still behaves: store, then edit, edit wins.+func TestEditAfterTheSentStoreStillApplies(t *testing.T) {+ repo, ctx := orderTestRepo(t)+ now := time.Now().UTC()++ require.NoError(t, repo.StoreSentMessageWithContext(+ ctx, orderMsgID, "[email protected]", orderChatJID,+ "ORIGINAL content", now, nil,+ ))+ require.NoError(t, repo.CreateMessage(ctx, editEvent(orderMsgID, "EDITED content", now.Add(time.Second))))++ stored, err := repo.GetMessageByIDAndDevice(orderDevice, orderMsgID)+ require.NoError(t, err)+ assert.Equal(t, "EDITED content", stored.Content)+}++// Control: with no edit recorded, a sent store writes its content normally. The+// guard must not freeze content for every message that happens to be re-stored.+func TestSentStoreWritesContentWhenNoEditExists(t *testing.T) {+ repo, ctx := orderTestRepo(t)+ now := time.Now().UTC()++ require.NoError(t, repo.StoreSentMessageWithContext(+ ctx, orderMsgID, "[email protected]", orderChatJID, "first", now, nil))+ require.NoError(t, repo.StoreSentMessageWithContext(+ ctx, orderMsgID, "[email protected]", orderChatJID, "second", now, nil))++ stored, err := repo.GetMessageByIDAndDevice(orderDevice, orderMsgID)+ require.NoError(t, err)+ assert.Equal(t, "second", stored.Content)+}++// Interleaves the two writers repeatedly. The real guarantee is structural — the+// edit check is an EXISTS inside the UPDATE, so there is no window between check+// and write — and this exercises it under actual contention rather than relying+// on a hand-picked order. Content must never come back as the original.+func TestConcurrentSentStoreAndEditNeverYieldsOriginalContent(t *testing.T) {+ const rounds = 40++ for i := 0; i < rounds; i++ {+ repo, ctx := orderTestRepo(t)+ now := time.Now().UTC()+ id := orderMsgID++ var wg sync.WaitGroup+ wg.Add(2)+ start := make(chan struct{})++ go func() {+ defer wg.Done()+ <-start+ _ = repo.StoreSentMessageWithContext(+ ctx, id, "[email protected]", orderChatJID, "ORIGINAL content", now, nil)+ }()+ go func() {+ defer wg.Done()+ <-start+ _ = repo.CreateMessage(ctx, editEvent(id, "EDITED content", now))+ }()++ close(start)+ wg.Wait()++ stored, err := repo.GetMessageByIDAndDevice(orderDevice, id)+ require.NoError(t, err)+ if stored == nil {+ continue // both writers failed to land a row; nothing to assert+ }+ // The edit may or may not have won the ordering, but once it has been+ // RECORDED the stored content must reflect it — never the original.+ edits, err := repo.GetMessageEdits(id, orderDevice)+ require.NoError(t, err)+ if len(edits) > 0 {+ require.Equal(t, "EDITED content", stored.Content,+ "round %d: the original store clobbered a recorded edit", i)+ }+ }+}diff --git a/src/infrastructure/whatsapp/auto_reply.go b/src/infrastructure/whatsapp/auto_reply.goindex 438f2507..1f73d410 100644--- a/src/infrastructure/whatsapp/auto_reply.go+++ b/src/infrastructure/whatsapp/auto_reply.go@@ -88,10 +88,7 @@ func handleAutoReply(ctx context.Context, evt *events.Message, chatStorageRepo d// Store the auto-reply message in chat storage if send was successfulif chatStorageRepo != nil {// Get our own JID as sender- senderJID := ""- if client.Store.ID != nil {- senderJID = client.Store.ID.String()- }+ senderJID := OwnSenderJID(client)// Store the sent auto-reply messageif err := chatStorageRepo.StoreSentMessageWithContext(diff --git a/src/infrastructure/whatsapp/own_sender.go b/src/infrastructure/whatsapp/own_sender.gonew file mode 100644index 00000000..40dd3bec--- /dev/null+++ b/src/infrastructure/whatsapp/own_sender.go@@ -0,0 +1,24 @@+package whatsapp++import "go.mau.fi/whatsmeow"++// OwnSenderJID returns the JID to record as the sender of a message this device+// sent, in the same non-AD form every other sender in chat storage already uses.+//+// client.Store.ID carries the device suffix (for example+// "6281234567890:[email protected]"), because a linked companion is never+// device 0. Stored verbatim, a sent message becomes the only row in the table+// whose sender is not a plain user JID — and mergeReplyContext copies that value+// straight into ContextInfo.Participant, where a device-suffixed JID matches no+// participant of the chat, so recipients cannot attribute the quoted message.+//+// Every other path already normalises: CreateMessage stores+// normalizedSender.ToNonAD(), history sync uses client.Store.ID.ToNonAD(), and+// MarkAsRead uses client.Store.ID.ToNonAD(). This keeps the two sent-message+// paths consistent with them.+func OwnSenderJID(client *whatsmeow.Client) string {+ if client == nil || client.Store == nil || client.Store.ID == nil {+ return ""+ }+ return client.Store.ID.ToNonAD().String()+}diff --git a/src/infrastructure/whatsapp/own_sender_test.go b/src/infrastructure/whatsapp/own_sender_test.gonew file mode 100644index 00000000..373294cc--- /dev/null+++ b/src/infrastructure/whatsapp/own_sender_test.go@@ -0,0 +1,40 @@+package whatsapp++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "go.mau.fi/whatsmeow"+ waStore "go.mau.fi/whatsmeow/store"+ "go.mau.fi/whatsmeow/types"+)++func clientWithID(jid types.JID) *whatsmeow.Client {+ return &whatsmeow.Client{Store: &waStore.Device{ID: &jid}}+}++// A linked companion is never device 0, so the raw Store.ID always carries a+// device suffix. That suffix must not reach chat storage.+func TestOwnSenderJIDStripsTheDeviceSuffix(t *testing.T) {+ jid := types.JID{User: "6281234567890", Server: types.DefaultUserServer, Device: 32}++ // Control: without normalisation this is what would be stored. If this ever+ // stops carrying the suffix the test below proves nothing, so assert it.+ require.Equal(t, "6281234567890:[email protected]", jid.String())++ assert.Equal(t, "[email protected]", OwnSenderJID(clientWithID(jid)))+}++func TestOwnSenderJIDLeavesAPlainJIDAlone(t *testing.T) {+ jid := types.JID{User: "6281234567890", Server: types.DefaultUserServer}+ assert.Equal(t, "[email protected]", OwnSenderJID(clientWithID(jid)))+}++// Callers store whatever comes back; an empty string is the existing "unknown+// sender" behaviour and must survive a nil client, store, or ID.+func TestOwnSenderJIDIsEmptyWhenUnavailable(t *testing.T) {+ assert.Empty(t, OwnSenderJID(nil))+ assert.Empty(t, OwnSenderJID(&whatsmeow.Client{}))+ assert.Empty(t, OwnSenderJID(&whatsmeow.Client{Store: &waStore.Device{}}))+}diff --git a/src/usecase/message.go b/src/usecase/message.goindex 29ff1082..ecbc89c7 100644--- a/src/usecase/message.go+++ b/src/usecase/message.go@@ -17,9 +17,11 @@ import ("github.com/sirupsen/logrus""go.mau.fi/whatsmeow""go.mau.fi/whatsmeow/appstate"+ "go.mau.fi/whatsmeow/proto/waCommon""go.mau.fi/whatsmeow/proto/waE2E""go.mau.fi/whatsmeow/proto/waSyncAction""go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events""google.golang.org/protobuf/proto")@@ -389,6 +391,76 @@ func (service serviceMessage) DeleteMessage(ctx context.Context, request domainMreturn service.deleteStoredMessage(ctx, client, request.MessageID, dataWaRecipient.ToNonAD().String())}+// updateStoredMessage mirrors an edit sent through the API into local chat+// storage, the same way deleteStoredMessage does for a revoke or delete.+//+// An edit that ARRIVES from another device is already applied: CreateMessage+// spots the MESSAGE_EDIT protocol message and calls storeEditedMessage. An edit+// we send ourselves is never echoed back to us, so nothing applied it, and the+// stored copy keeps the text as first sent — indefinitely.+//+// That matters beyond the chat viewer, because mergeReplyContext builds a+// reply's quoted context from the stored copy. Quoting a message that was edited+// therefore sends the recipient the PRE-EDIT text, so the quote can show wording+// the message no longer contains.+//+// The edit is replayed in the ProtocolMessage shape CreateMessage already+// recognises, so it runs through the existing, tested edit path (content update+// plus a message_edits history row) rather than a second implementation that+// could drift from it.+//+// This is an adapter for local storage, not a claim of equivalence with a+// dispatched event. whatsmeow's ParseWebMessage unwraps MESSAGE_EDIT before a+// history-synced edit is handled (Info.ID becomes the target id and Message+// becomes the edited content); only the live receive path leaves the+// ProtocolMessage intact.+func (service serviceMessage) updateStoredMessage(+ ctx context.Context,+ client *whatsmeow.Client,+ messageID string,+ recipient types.JID,+ newContent string,+ editEventID string,+ editedAt time.Time,+) error {+ if service.chatStorageRepo == nil {+ return fmt.Errorf("WhatsApp action succeeded, but local message %s could not be updated without chat storage", messageID)+ }++ senderJID := types.EmptyJID+ if client != nil && client.Store != nil && client.Store.ID != nil {+ senderJID = *client.Store.ID+ }++ evt := &events.Message{+ Info: types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: recipient,+ Sender: senderJID,+ IsFromMe: true,+ },+ ID: editEventID,+ Timestamp: editedAt,+ },+ Message: &waE2E.Message{+ ProtocolMessage: &waE2E.ProtocolMessage{+ Type: waE2E.ProtocolMessage_MESSAGE_EDIT.Enum(),+ Key: &waCommon.MessageKey{+ ID: proto.String(messageID),+ RemoteJID: proto.String(recipient.String()),+ FromMe: proto.Bool(true),+ },+ EditedMessage: &waE2E.Message{Conversation: proto.String(newContent)},+ },+ },+ }++ if err := service.chatStorageRepo.CreateMessage(ctx, evt); err != nil {+ return fmt.Errorf("WhatsApp action succeeded, but failed to update local message %s: %w", messageID, err)+ }+ return nil+}+func (service serviceMessage) UpdateMessage(ctx context.Context, request domainMessage.UpdateMessageRequest) (response domainMessage.GenericResponse, err error) {if err = validations.ValidateUpdateMessage(ctx, request); err != nil {return response, err@@ -399,17 +471,21 @@ func (service serviceMessage) UpdateMessage(ctx context.Context, request domainMreturn response, pkgError.ErrWaCLI}- dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)+ dataWaRecipient, err := service.validateJID(client, request.Phone)if err != nil {return response, err}msg := &waE2E.Message{Conversation: proto.String(request.Message)}- ts, err := client.SendMessage(ctx, dataWaRecipient, client.BuildEdit(dataWaRecipient, request.MessageID, msg))+ ts, err := service.sendMessage(ctx, client, dataWaRecipient, client.BuildEdit(dataWaRecipient, request.MessageID, msg))if err != nil {return response, err}+ if err := service.updateStoredMessage(ctx, client, request.MessageID, dataWaRecipient.ToNonAD(), request.Message, ts.ID, ts.Timestamp); err != nil {+ return response, err+ }+response.MessageID = ts.IDresponse.Status = fmt.Sprintf("Update message success %s (server timestamp: %s)", request.Phone, ts.Timestamp)return response, nildiff --git a/src/usecase/message_update_sync_test.go b/src/usecase/message_update_sync_test.gonew file mode 100644index 00000000..54c10933--- /dev/null+++ b/src/usecase/message_update_sync_test.go@@ -0,0 +1,92 @@+package usecase++import (+ "errors"+ "testing"++ domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// An edit sent through the API must land in chat storage, exactly as an edit+// that arrives from another device already does.+//+// Chat storage is what mergeReplyContext quotes from, so an unsynced edit means+// every later reply to that message quotes the recipient the pre-edit text.+func TestUpdateMessageSyncsEditToChatStorage(t *testing.T) {+ service, repo, ctx := newMessageActionTestService(t, nil)++ _, err := service.UpdateMessage(ctx, domainMessage.UpdateMessageRequest{+ MessageID: "message-1",+ Phone: "[email protected]",+ Message: "edited content",+ })+ require.NoError(t, err)++ stored, err := repo.GetMessageByIDAndDevice("[email protected]", "message-1")+ require.NoError(t, err)+ require.NotNil(t, stored)+ assert.Equal(t, "edited content", stored.Content)+}++// The edit history row is what makes an edit auditable after the fact, and the+// inbound path already writes one — the API path must not be the odd one out.+func TestUpdateMessageRecordsEditHistory(t *testing.T) {+ service, repo, ctx := newMessageActionTestService(t, nil)++ _, err := service.UpdateMessage(ctx, domainMessage.UpdateMessageRequest{+ MessageID: "message-1",+ Phone: "[email protected]",+ Message: "edited content",+ })+ require.NoError(t, err)++ edits, err := repo.GetMessageEdits("message-1", "[email protected]")+ require.NoError(t, err)+ require.Len(t, edits, 1)+ assert.Equal(t, "stored content", edits[0].PreviousContent)+ assert.Equal(t, "edited content", edits[0].NewContent)+}++// Only the device that owns the conversation is touched. Message IDs are unique+// per device row, so a sibling device's copy must be left exactly as it was.+func TestUpdateMessageLeavesOtherDevicesAlone(t *testing.T) {+ service, repo, ctx := newMessageActionTestService(t, nil)++ _, err := service.UpdateMessage(ctx, domainMessage.UpdateMessageRequest{+ MessageID: "message-1",+ Phone: "[email protected]",+ Message: "edited content",+ })+ require.NoError(t, err)++ other, err := repo.GetMessageByIDAndDevice("[email protected]", "message-1")+ require.NoError(t, err)+ require.NotNil(t, other)+ assert.Equal(t, "stored content", other.Content)+}++// Mirrors TestMessageActionsKeepStoredMessageWhenWhatsAppFails: nothing local+// changes when the edit never reached WhatsApp, so storage cannot drift ahead of+// what the recipient actually has.+func TestUpdateMessageKeepsStoredContentWhenWhatsAppFails(t *testing.T) {+ remoteErr := errors.New("whatsapp unavailable")+ service, repo, ctx := newMessageActionTestService(t, remoteErr)++ _, err := service.UpdateMessage(ctx, domainMessage.UpdateMessageRequest{+ MessageID: "message-1",+ Phone: "[email protected]",+ Message: "edited content",+ })+ require.ErrorIs(t, err, remoteErr)++ stored, lookupErr := repo.GetMessageByIDAndDevice("[email protected]", "message-1")+ require.NoError(t, lookupErr)+ require.NotNil(t, stored)+ assert.Equal(t, "stored content", stored.Content)++ edits, lookupErr := repo.GetMessageEdits("message-1", "[email protected]")+ require.NoError(t, lookupErr)+ assert.Empty(t, edits)+}diff --git a/src/usecase/send.go b/src/usecase/send.goindex 30abde16..0508de53 100644--- a/src/usecase/send.go+++ b/src/usecase/send.go@@ -208,10 +208,7 @@ func (service serviceSend) wrapSendMessage(ctx context.Context, client *whatsmeo}// Store the sent message using chatstorage- senderJID := ""- if client.Store.ID != nil {- senderJID = client.Store.ID.String()- }+ senderJID := whatsapp.OwnSenderJID(client)// Store message asynchronously with timeout.// Preserve device context (for device_id scoping) but detach from request cancellation.@@ -234,6 +231,32 @@ func (service serviceSend) wrapSendMessage(ctx context.Context, client *whatsmeoreturn ts, nil}+// normalizeStoredSender renders a stored sender in the plain user form a quote's+// Participant requires.+//+// The reader cannot trust what is persisted. Rows written before senders were+// normalised on the way in still carry AD/device identity+// ("628123456789:[email protected]"), and a device-suffixed JID matches no+// participant of a chat, so the recipient cannot attribute the quoted message.+// Normalising here covers those rows without a migration, and mirrors+// RevokeMessage, which parses and LID-normalises a stored sender for the same+// reason. A value that will not parse is passed through untouched.+func normalizeStoredSender(ctx context.Context, sender string) string {+ // ParseJID does not report failure on a malformed value — it appends the+ // default server, so "not-a-jid" becomes "[email protected]". Only+ // touch a value that already carries one, so anything else survives verbatim+ // instead of being rewritten into a different unusable form.+ if !strings.Contains(sender, "@") {+ return sender+ }+ parsed, err := utils.ParseJID(sender)+ if err != nil {+ logrus.Warnf("Could not parse stored sender %q for reply context: %v", sender, err)+ return sender+ }+ return whatsapp.NormalizeJIDFromLID(ctx, parsed, whatsapp.ClientFromContext(ctx)).ToNonAD().String()+}+func (service serviceSend) mergeReplyContext(ctx context.Context, contextInfo *waE2E.ContextInfo, replyMessageID *string) *waE2E.ContextInfo {if replyMessageID == nil || *replyMessageID == "" {return contextInfo@@ -255,7 +278,7 @@ func (service serviceSend) mergeReplyContext(ctx context.Context, contextInfo *wcontextInfo = &waE2E.ContextInfo{}}contextInfo.StanzaID = replyMessageID- contextInfo.Participant = proto.String(message.Sender)+ contextInfo.Participant = proto.String(normalizeStoredSender(ctx, message.Sender))contextInfo.QuotedMessage = &waE2E.Message{Conversation: proto.String(message.Content),}diff --git a/src/usecase/send_test.go b/src/usecase/send_test.goindex ec6b1ba5..802e4a2f 100644--- a/src/usecase/send_test.go+++ b/src/usecase/send_test.go@@ -573,3 +573,43 @@ func TestSendForwardUnsupportedType(t *testing.T) {t.Fatalf("error = %q, want %q", genericErr.Error(), utils.ErrUnsupportedForwardType)}}++// A sender persisted before senders were normalised on the way in still carries+// AD/device identity. The quote reader must not trust it: a device-suffixed JID+// matches no participant of a chat, so the recipient cannot attribute the quote.+func TestMergeReplyContextNormalizesALegacyDeviceSuffixedSender(t *testing.T) {+ replyID := "3EB089B9D6ADD58153C561"+ repo := &replyMessageRepo{+ message: &domainChatStorage.Message{+ Sender: "628123456789:[email protected]", // written before the fix+ Content: "quoted message body",+ },+ }+ service := serviceSend{chatStorageRepo: repo}++ ctx := whatsapp.ContextWithDevice(context.Background(),+ whatsapp.NewDeviceInstance("[email protected]", nil, nil))+ got := service.mergeReplyContext(ctx, &waE2E.ContextInfo{}, &replyID)++ if got.GetParticipant() != "[email protected]" {+ t.Fatalf("expected the stored sender to be normalized, got %q", got.GetParticipant())+ }+}++// A stored value that will not parse must pass through rather than be dropped:+// a wrong participant is recoverable, an empty one loses the quote entirely.+func TestMergeReplyContextPassesThroughAnUnparseableSender(t *testing.T) {+ replyID := "3EB089B9D6ADD58153C561"+ repo := &replyMessageRepo{+ message: &domainChatStorage.Message{Sender: "not-a-jid", Content: "body"},+ }+ service := serviceSend{chatStorageRepo: repo}++ ctx := whatsapp.ContextWithDevice(context.Background(),+ whatsapp.NewDeviceInstance("[email protected]", nil, nil))+ got := service.mergeReplyContext(ctx, &waE2E.ContextInfo{}, &replyID)++ if got.GetParticipant() != "not-a-jid" {+ t.Fatalf("expected the raw sender to survive, got %q", got.GetParticipant())+ }+}