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(chat): add on-demand history sync endpoint (#834)

Kizuno1896c3b69e47ff
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 4da998ec..ec0391d2 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -2632,6 +2632,67 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
+ /chat/{chat_jid}/history:
+ post:
+ operationId: requestChatHistory
+ tags:
+ - chat
+ summary: Request older chat history from the phone
+ description: >-
+ Asks the phone for older messages of a chat on demand (what WhatsApp
+ Web does when you scroll up / "load older messages"). The request is
+ anchored at the oldest message currently stored locally for that
+ chat, so the chat must already have at least one stored message. The
+ phone answers asynchronously with a history sync event that gets
+ persisted into chat storage; this endpoint only confirms the request
+ was sent, it does not return the older messages directly.
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
+ - in: path
+ name: chat_jid
+ schema:
+ type: string
+ required: true
+ description: Chat JID (e.g., [email protected] for individual or [email protected] for group). Percent-encoded values (e.g., groupid%40g.us) are accepted.
+ example: '[email protected]'
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ count:
+ type: integer
+ default: 50
+ minimum: 1
+ maximum: 500
+ example: 50
+ description: Number of older messages to request from the phone
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RequestChatHistoryResponse'
+ '400':
+ description: Bad Request (e.g. missing chat_jid, count out of range, or chat has no stored messages to anchor on)
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorBadRequest'
+ '401':
+ description: Unauthorized
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorUnauthorized'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
/chat/{chat_jid}/pin:
post:
operationId: pinChat
@@ -5431,6 +5492,37 @@ components:
example: '2024-01-15T10:31:00Z'
description: When the reaction was received
+ RequestChatHistoryResponse:
+ type: object
+ properties:
+ status:
+ type: integer
+ example: 200
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: History sync requested successfully
+ results:
+ type: object
+ properties:
+ status:
+ type: string
+ example: requested
+ chat_jid:
+ type: string
+ example: '[email protected]'
+ requested_count:
+ type: integer
+ example: 50
+ anchor_message_id:
+ type: string
+ example: '3EB0C767D82B0A0D1234'
+ anchor_timestamp:
+ type: string
+ format: date-time
+ example: '2026-05-16T08:00:00Z'
PinChatResponse:
type: object
properties:
diff --git a/readme.md b/readme.md
index 36765a2f..e0121acd 100644
--- a/readme.md
+++ b/readme.md
@@ -713,6 +713,7 @@ You may also fork or modify the source code.
| ✅ | Pin Chat | POST | /chat/:chat_jid/pin |
| ✅ | Archive Chat | POST | /chat/:chat_jid/archive |
| ✅ | Set Disappearing Messages | POST | /chat/:chat_jid/disappearing |
+| ✅ | Request Chat History (Load Older Msgs) | POST | /chat/:chat_jid/history |
| ✅ | Chatwoot Sync History | POST | /chatwoot/sync |
| ✅ | Chatwoot Sync Status | GET | /chatwoot/sync/status |
| ✅ | List Chatwoot Configurations | GET | /chatwoot/configs |
diff --git a/src/domains/chat/chat.go b/src/domains/chat/chat.go
index 3ac8c361..9d2fad9b 100644
--- a/src/domains/chat/chat.go
+++ b/src/domains/chat/chat.go
@@ -93,6 +93,20 @@ type SetDisappearingTimerResponse struct {
TimerSeconds uint32 `json:"timer_seconds"`
}
+// RequestChatHistory operations (on-demand history sync)
+type RequestChatHistoryRequest struct {
+ ChatJID string `json:"chat_jid" uri:"chat_jid"`
+ Count int `json:"count"`
+}
+
+type RequestChatHistoryResponse struct {
+ Status string `json:"status"`
+ ChatJID string `json:"chat_jid"`
+ RequestedCount int `json:"requested_count"`
+ AnchorMessageID string `json:"anchor_message_id"`
+ AnchorTimestamp string `json:"anchor_timestamp"`
+}
+
// Archive Chat operations
type ArchiveChatRequest struct {
ChatJID string `json:"chat_jid" uri:"chat_jid"`
diff --git a/src/domains/chat/interfaces.go b/src/domains/chat/interfaces.go
index 9f5f4e2d..dcacbef5 100644
--- a/src/domains/chat/interfaces.go
+++ b/src/domains/chat/interfaces.go
@@ -11,4 +11,8 @@ type IChatUsecase interface {
PinChat(ctx context.Context, request PinChatRequest) (response PinChatResponse, err error)
SetDisappearingTimer(ctx context.Context, request SetDisappearingTimerRequest) (response SetDisappearingTimerResponse, err error)
ArchiveChat(ctx context.Context, request ArchiveChatRequest) (response ArchiveChatResponse, err error)
+ // RequestChatHistory asks the phone (via an on-demand history sync request)
+ // for older messages of a chat, anchored at the oldest message currently
+ // stored for that chat.
+ RequestChatHistory(ctx context.Context, request RequestChatHistoryRequest) (response RequestChatHistoryResponse, err error)
}
diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.go
index 36bf76ef..fe8d3ee2 100644
--- a/src/domains/chatstorage/interfaces.go
+++ b/src/domains/chatstorage/interfaces.go
@@ -31,6 +31,10 @@ type IChatStorageRepository interface {
GetMessageByIDChatAndDevice(deviceID, chatJID, id string) (*Message, error) // Full storage identity lookup for chat-scoped flows
GetMessageEdits(originalMessageID, deviceID string) ([]*MessageEdit, error)
GetMessages(filter *MessageFilter) ([]*Message, error)
+ // GetOldestMessageByDevice returns the earliest stored message for a chat,
+ // used to anchor on-demand history sync requests. Returns nil (no error)
+ // when the chat has no stored messages.
+ GetOldestMessageByDevice(deviceID, chatJID string) (*Message, error)
SearchMessages(deviceID, chatJID, searchText string, limit int) ([]*Message, error) // Database-level search with device isolation
DeleteMessage(id, chatJID string) error
DeleteMessageByDevice(deviceID, id, chatJID string) error
diff --git a/src/infrastructure/chatstorage/sqlite_repository_message_lookup.go b/src/infrastructure/chatstorage/sqlite_repository_message_lookup.go
index 7adda25d..6de3ecc3 100644
--- a/src/infrastructure/chatstorage/sqlite_repository_message_lookup.go
+++ b/src/infrastructure/chatstorage/sqlite_repository_message_lookup.go
@@ -26,3 +26,31 @@ func (r *SQLiteRepository) GetMessageByIDChatAndDevice(deviceID, chatJID, id str
}
return message, err
}
+
+// GetOldestMessageByDevice returns the earliest stored message for a chat,
+// scoped to the device for data isolation. Used to anchor on-demand history
+// sync requests, which need the oldest known message ID/timestamp to ask the
+// phone for anything older. Returns (nil, nil) when the chat has no stored
+// messages yet.
+//
+// Locally synthesized rows (e.g. incoming calls, stored as media_type "call"
+// with id "call:<callID>") are excluded: the phone only recognizes real
+// WebMessageInfo IDs as history-sync anchors, so a call row would repeatedly
+// produce an invalid oldest_msg_id.
+func (r *SQLiteRepository) GetOldestMessageByDevice(deviceID, chatJID string) (*domainChatStorage.Message, error) {
+ query := `
+ SELECT 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
+ FROM messages
+ WHERE chat_jid = ? AND device_id = ? AND (media_type IS NULL OR media_type != 'call')
+ ORDER BY timestamp ASC
+ LIMIT 1
+ `
+
+ message, err := r.scanMessage(r.db.QueryRow(query, chatJID, deviceID))
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ return message, err
+}
diff --git a/src/infrastructure/chatstorage/sqlite_repository_test.go b/src/infrastructure/chatstorage/sqlite_repository_test.go
index d89cea72..2b33f146 100644
--- a/src/infrastructure/chatstorage/sqlite_repository_test.go
+++ b/src/infrastructure/chatstorage/sqlite_repository_test.go
@@ -385,6 +385,113 @@ func getMessagesForTest(t *testing.T, repo *SQLiteRepository, deviceID, chatJID
return messages
}
+// TestSQLiteRepositoryGetOldestMessageByDevice pins the on-demand history sync
+// anchor lookup: it must return the earliest message by timestamp for the
+// given chat/device, ignoring newer messages and other devices' messages, and
+// return (nil, nil) for a chat with nothing stored yet.
+func TestSQLiteRepositoryGetOldestMessageByDevice(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ deviceID := "[email protected]"
+ otherDeviceID := "[email protected]"
+ chatJID := "[email protected]"
+ base := time.Date(2026, time.June, 19, 8, 0, 0, 0, time.UTC)
+
+ if err := repo.StoreChat(&domainChatStorage.Chat{
+ DeviceID: deviceID,
+ JID: chatJID,
+ Name: chatJID,
+ LastMessageTime: base,
+ }); err != nil {
+ t.Fatalf("store chat: %v", err)
+ }
+
+ got, err := repo.GetOldestMessageByDevice(deviceID, chatJID)
+ if err != nil {
+ t.Fatalf("get oldest message (empty chat): %v", err)
+ }
+ if got != nil {
+ t.Fatalf("expected nil for chat with no stored messages, got %+v", got)
+ }
+
+ messages := []*domainChatStorage.Message{
+ {ID: "msg-newest", ChatJID: chatJID, DeviceID: deviceID, Sender: "[email protected]", Content: "newest", Timestamp: base.Add(2 * time.Hour)},
+ {ID: "msg-oldest", ChatJID: chatJID, DeviceID: deviceID, Sender: "[email protected]", Content: "oldest", Timestamp: base},
+ {ID: "msg-middle", ChatJID: chatJID, DeviceID: deviceID, Sender: "[email protected]", Content: "middle", Timestamp: base.Add(1 * time.Hour)},
+ // Older timestamp but a different device — must not be selected.
+ {ID: "msg-other-device", ChatJID: chatJID, DeviceID: otherDeviceID, Sender: "[email protected]", Content: "other device", Timestamp: base.Add(-1 * time.Hour)},
+ }
+ if err := repo.StoreMessagesBatch(messages); err != nil {
+ t.Fatalf("store messages batch: %v", err)
+ }
+
+ got, err = repo.GetOldestMessageByDevice(deviceID, chatJID)
+ if err != nil {
+ t.Fatalf("get oldest message: %v", err)
+ }
+ if got == nil {
+ t.Fatal("expected the oldest stored message, got nil")
+ }
+ if got.ID != "msg-oldest" {
+ t.Fatalf("oldest message ID = %q, want %q", got.ID, "msg-oldest")
+ }
+}
+
+// TestSQLiteRepositoryGetOldestMessageByDeviceSkipsSyntheticCallRows pins the
+// history-sync anchor fix: a synthetic call row (media_type "call", id
+// "call:<callID>") stored by CreateIncomingCallRecord is not a real WhatsApp
+// message the phone can recognize as a history-sync anchor, so it must never
+// be selected over an older-but-real message.
+func TestSQLiteRepositoryGetOldestMessageByDeviceSkipsSyntheticCallRows(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ deviceID := "[email protected]"
+ chatJID := "[email protected]"
+ base := time.Date(2026, time.June, 19, 8, 0, 0, 0, time.UTC)
+
+ if err := repo.StoreChat(&domainChatStorage.Chat{
+ DeviceID: deviceID,
+ JID: chatJID,
+ Name: chatJID,
+ LastMessageTime: base,
+ }); err != nil {
+ t.Fatalf("store chat: %v", err)
+ }
+
+ // Synthetic call row, older than the real message.
+ if err := repo.StoreMessage(&domainChatStorage.Message{
+ ID: "call:call-1",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ Sender: "[email protected]",
+ Content: "Incoming call",
+ Timestamp: base.Add(-1 * time.Hour),
+ MediaType: "call",
+ }); err != nil {
+ t.Fatalf("store synthetic call row: %v", err)
+ }
+
+ if err := repo.StoreMessage(&domainChatStorage.Message{
+ ID: "msg-real",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ Sender: "[email protected]",
+ Content: "real message",
+ Timestamp: base,
+ }); err != nil {
+ t.Fatalf("store real message: %v", err)
+ }
+
+ got, err := repo.GetOldestMessageByDevice(deviceID, chatJID)
+ if err != nil {
+ t.Fatalf("get oldest message: %v", err)
+ }
+ if got == nil {
+ t.Fatal("expected the real message, got nil")
+ }
+ if got.ID != "msg-real" {
+ t.Fatalf("oldest message ID = %q, want %q (synthetic call row must be excluded)", got.ID, "msg-real")
+ }
+}
+
func countMessageReactions(t *testing.T, repo *SQLiteRepository) int {
t.Helper()
var count int
diff --git a/src/infrastructure/whatsapp/chatstorage_wrapper.go b/src/infrastructure/whatsapp/chatstorage_wrapper.go
index b2bd5097..7e68e21a 100644
--- a/src/infrastructure/whatsapp/chatstorage_wrapper.go
+++ b/src/infrastructure/whatsapp/chatstorage_wrapper.go
@@ -126,6 +126,14 @@ func (r *deviceChatStorage) GetMessages(filter *domainChatStorage.MessageFilter)
return r.base.GetMessages(filter)
}
+func (r *deviceChatStorage) GetOldestMessageByDevice(deviceID, chatJID string) (*domainChatStorage.Message, error) {
+ targetDeviceID := deviceID
+ if targetDeviceID == "" {
+ targetDeviceID = r.deviceID
+ }
+ return r.base.GetOldestMessageByDevice(targetDeviceID, chatJID)
+}
+
func (r *deviceChatStorage) SearchMessages(deviceID, chatJID, searchText string, limit int) ([]*domainChatStorage.Message, error) {
targetDeviceID := deviceID
if targetDeviceID == "" {
diff --git a/src/infrastructure/whatsapp/history_sync.go b/src/infrastructure/whatsapp/history_sync.go
index ad1c8931..3f1c1f3b 100644
--- a/src/infrastructure/whatsapp/history_sync.go
+++ b/src/infrastructure/whatsapp/history_sync.go
@@ -67,8 +67,11 @@ func processHistorySync(ctx context.Context, data *waHistorySync.HistorySync, ch
log.Infof("Processing history sync type: %s", syncType.String())
switch syncType {
- case waHistorySync.HistorySync_INITIAL_BOOTSTRAP, waHistorySync.HistorySync_RECENT:
- // Process conversation messages
+ case waHistorySync.HistorySync_INITIAL_BOOTSTRAP, waHistorySync.HistorySync_RECENT, waHistorySync.HistorySync_ON_DEMAND:
+ // Process conversation messages. ON_DEMAND is the phone's reply to a
+ // history sync request built with Client.BuildHistorySyncRequest (older
+ // messages fetched on demand, e.g. "load older messages"); it carries
+ // conversations in the same shape as INITIAL_BOOTSTRAP/RECENT.
return processConversationMessages(ctx, data, chatStorageRepo, client)
case waHistorySync.HistorySync_PUSH_NAME:
// Process push names to update chat names
@@ -295,10 +298,29 @@ func processConversationMessages(ctx context.Context, data *waHistorySync.Histor
EphemeralExpiration: ephemeralExpiration,
}
+ storeChat := true
+ if data.GetSyncType() == waHistorySync.HistorySync_ON_DEMAND {
+ // ON_DEMAND delivers messages older than the local anchor, so its
+ // batch timestamp must never move the chat's activity time backward
+ // or clobber flags (e.g. archived) that live history didn't touch.
+ // If the current state cannot be read, leave the chat row alone.
+ if existing, err := chatStorageRepo.GetChatByDevice(deviceID, chatJID); err != nil {
+ log.Warnf("Failed to load existing chat %s for on-demand merge, keeping stored metadata: %v", chatJID, err)
+ storeChat = false
+ } else if existing != nil {
+ if existing.LastMessageTime.After(chat.LastMessageTime) {
+ chat.LastMessageTime = existing.LastMessageTime
+ }
+ chat.Archived = existing.Archived
+ }
+ }
+
// Store or update the chat
- if err := chatStorageRepo.StoreChat(chat); err != nil {
- log.Warnf("Failed to store chat %s: %v", chatJID, err)
- continue
+ if storeChat {
+ if err := chatStorageRepo.StoreChat(chat); err != nil {
+ log.Warnf("Failed to store chat %s: %v", chatJID, err)
+ continue
+ }
}
// Store messages in batch
diff --git a/src/infrastructure/whatsapp/history_sync_test.go b/src/infrastructure/whatsapp/history_sync_test.go
index 4a63990f..84d663e8 100644
--- a/src/infrastructure/whatsapp/history_sync_test.go
+++ b/src/infrastructure/whatsapp/history_sync_test.go
@@ -122,6 +122,134 @@ func TestProcessConversationMessagesPersistsPollDefinitionWithoutText(t *testing
repo.definition.UpdatedAt, wantTimestamp)
}
+// TestProcessHistorySyncRoutesOnDemandToConversationMessages pins the
+// on-demand history sync routing fix: HISTORY_SYNC_ON_DEMAND (the phone's
+// reply to Client.BuildHistorySyncRequest, used for "load older messages")
+// must be persisted the same way as INITIAL_BOOTSTRAP/RECENT, not silently
+// dropped by the sync-type switch in processHistorySync.
+func TestProcessHistorySyncRoutesOnDemandToConversationMessages(t *testing.T) {
+ originalLog := log
+ log = waLog.Noop
+ defer func() { log = originalLog }()
+
+ deviceID := "[email protected]"
+ chatJID := "[email protected]"
+ repo := &historyMessageBatchRepoSpy{}
+ ctx := ContextWithDevice(context.Background(), NewDeviceInstance(deviceID, nil, nil))
+ syncType := waHistorySync.HistorySync_ON_DEMAND
+ timestamp := uint64(time.Date(2026, time.September, 6, 8, 0, 0, 0, time.UTC).Unix())
+ data := &waHistorySync.HistorySync{
+ SyncType: &syncType,
+ Conversations: []*waHistorySync.Conversation{{
+ ID: proto.String(chatJID),
+ Messages: []*waHistorySync.HistorySyncMsg{{Message: &waWeb.WebMessageInfo{
+ Key: &waCommon.MessageKey{
+ RemoteJID: proto.String(chatJID),
+ FromMe: proto.Bool(false),
+ ID: proto.String("older-msg-1"),
+ },
+ Message: &waE2E.Message{Conversation: proto.String("an older message")},
+ MessageTimestamp: &timestamp,
+ }}},
+ }},
+ }
+
+ if err := processHistorySync(ctx, data, repo, nil); err != nil {
+ t.Fatalf("processHistorySync: %v", err)
+ }
+
+ if repo.storeMessagesBatchCalls != 1 {
+ t.Fatalf("expected on-demand conversations to be persisted once, got %d calls", repo.storeMessagesBatchCalls)
+ }
+ if len(repo.lastBatch) != 1 || repo.lastBatch[0].ID != "older-msg-1" {
+ t.Fatalf("unexpected persisted batch: %+v", repo.lastBatch)
+ }
+}
+
+// TestProcessConversationMessagesOnDemandPreservesNewerChatMetadata pins the
+// on-demand chat-metadata regression: HISTORY_SYNC_ON_DEMAND carries messages
+// older than the local anchor, so its batch timestamp must never move an
+// already-newer LastMessageTime backward, nor unarchive an archived chat.
+func TestProcessConversationMessagesOnDemandPreservesNewerChatMetadata(t *testing.T) {
+ originalLog := log
+ log = waLog.Noop
+ defer func() { log = originalLog }()
+
+ deviceID := "[email protected]"
+ chatJID := "[email protected]"
+ existingLastMessageTime := time.Date(2026, time.September, 6, 12, 0, 0, 0, time.UTC)
+ repo := &historyMessageBatchRepoSpy{
+ existingChat: &domainChatStorage.Chat{
+ DeviceID: deviceID,
+ JID: chatJID,
+ LastMessageTime: existingLastMessageTime,
+ Archived: true,
+ },
+ }
+ ctx := ContextWithDevice(context.Background(), NewDeviceInstance(deviceID, nil, nil))
+ syncType := waHistorySync.HistorySync_ON_DEMAND
+ olderTimestamp := uint64(time.Date(2026, time.September, 1, 8, 0, 0, 0, time.UTC).Unix())
+ data := &waHistorySync.HistorySync{
+ SyncType: &syncType,
+ Conversations: []*waHistorySync.Conversation{{
+ ID: proto.String(chatJID),
+ Messages: []*waHistorySync.HistorySyncMsg{{Message: &waWeb.WebMessageInfo{
+ Key: &waCommon.MessageKey{
+ RemoteJID: proto.String(chatJID),
+ FromMe: proto.Bool(false),
+ ID: proto.String("older-msg-2"),
+ },
+ Message: &waE2E.Message{Conversation: proto.String("an even older message")},
+ MessageTimestamp: &olderTimestamp,
+ }}},
+ }},
+ }
+
+ if err := processConversationMessages(ctx, data, repo, nil); err != nil {
+ t.Fatalf("processConversationMessages: %v", err)
+ }
+
+ if repo.lastStoredChat == nil {
+ t.Fatal("expected chat to be stored")
+ }
+ if !repo.lastStoredChat.LastMessageTime.Equal(existingLastMessageTime) {
+ t.Fatalf("expected LastMessageTime to stay at %s, got %s", existingLastMessageTime, repo.lastStoredChat.LastMessageTime)
+ }
+ if !repo.lastStoredChat.Archived {
+ t.Fatal("expected Archived to remain true after on-demand sync")
+ }
+}
+
+type historyMessageBatchRepoSpy struct {
+ domainChatStorage.IChatStorageRepository
+ storeMessagesBatchCalls int
+ lastBatch []*domainChatStorage.Message
+ existingChat *domainChatStorage.Chat
+ lastStoredChat *domainChatStorage.Chat
+}
+
+func (r *historyMessageBatchRepoSpy) StoreChat(chat *domainChatStorage.Chat) error {
+ r.lastStoredChat = chat
+ return nil
+}
+
+func (r *historyMessageBatchRepoSpy) GetChatByDevice(_, _ string) (*domainChatStorage.Chat, error) {
+ return r.existingChat, nil
+}
+
+func (r *historyMessageBatchRepoSpy) StoreMessagesBatch(messages []*domainChatStorage.Message) error {
+ r.storeMessagesBatchCalls++
+ r.lastBatch = messages
+ return nil
+}
+
+func (r *historyMessageBatchRepoSpy) GetChatNameWithPushName(jid types.JID, _ string, _ string, pushName string) string {
+ if pushName != "" {
+ return pushName
+ }
+ return jid.String()
+}
+
type historyReactionRepoSpy struct {
domainChatStorage.IChatStorageRepository
createReactionCalls int
diff --git a/src/ui/rest/chat.go b/src/ui/rest/chat.go
index 5addb1d5..5f016e1b 100644
--- a/src/ui/rest/chat.go
+++ b/src/ui/rest/chat.go
@@ -23,6 +23,7 @@ func InitRestChat(app fiber.Router, service domainChat.IChatUsecase) Chat {
app.Post("/chat/:chat_jid/pin", rest.PinChat)
app.Post("/chat/:chat_jid/disappearing", rest.SetDisappearingTimer)
app.Post("/chat/:chat_jid/archive", rest.ArchiveChat)
+ app.Post("/chat/:chat_jid/history", rest.RequestChatHistory)
return rest
}
@@ -205,6 +206,47 @@ func (controller *Chat) ArchiveChat(c fiber.Ctx) error {
})
}
+func (controller *Chat) RequestChatHistory(c fiber.Ctx) error {
+ var request domainChat.RequestChatHistoryRequest
+
+ // Parse path parameter
+ chatJID, err := chatJIDParam(c)
+ if err != nil {
+ return c.Status(400).JSON(utils.ResponseData{
+ Status: 400,
+ Code: "BAD_REQUEST",
+ Message: "invalid chat_jid path parameter: " + err.Error(),
+ Results: nil,
+ })
+ }
+ // Parse JSON body (optional — count defaults when the body is empty).
+ // Fiber v3.4.0's Bind().Body() picks a binder from Content-Type and
+ // returns ErrUnprocessableEntity when the body is empty and no
+ // Content-Type is set, so binding is skipped for an empty body.
+ if len(c.Body()) > 0 {
+ if err := c.Bind().Body(&request); err != nil {
+ return c.Status(400).JSON(utils.ResponseData{
+ Status: 400,
+ Code: "BAD_REQUEST",
+ Message: "Invalid request body",
+ Results: nil,
+ })
+ }
+ }
+ // Route JID is authoritative; a body chat_jid must never override it.
+ request.ChatJID = chatJID
+
+ response, err := controller.Service.RequestChatHistory(whatsapp.ContextWithDevice(c.Context(), getDeviceFromCtx(c)), request)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "History sync requested successfully",
+ Results: response,
+ })
+}
+
// chatJIDParam returns the chat_jid path parameter with percent-encoding
// decoded. Fiber does not unescape path params, so URL-encoding clients send
// "...%40g.us" which would miss every chat-storage lookup. strings.Clone
diff --git a/src/ui/rest/chat_test.go b/src/ui/rest/chat_test.go
index ec8e704f..d4f8acd0 100644
--- a/src/ui/rest/chat_test.go
+++ b/src/ui/rest/chat_test.go
@@ -1,11 +1,14 @@
package rest
import (
+ "context"
"encoding/json"
"io"
"net/http/httptest"
+ "strings"
"testing"
+ domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/gofiber/fiber/v3"
"github.com/stretchr/testify/require"
@@ -67,6 +70,7 @@ func TestChatJIDParamRejectsMalformedEscape(t *testing.T) {
resp, err := app.Test(req)
require.NoError(t, err)
+ defer resp.Body.Close()
require.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
@@ -76,3 +80,77 @@ func TestChatJIDParamRejectsMalformedEscape(t *testing.T) {
require.Equal(t, "BAD_REQUEST", envelope.Code)
require.Contains(t, envelope.Message, "invalid chat_jid path parameter")
}
+
+// requestChatHistorySpy is a minimal domainChat.IChatUsecase stub that only
+// records the RequestChatHistory call, for exercising the REST handler alone.
+type requestChatHistorySpy struct {
+ lastRequest domainChat.RequestChatHistoryRequest
+ calls int
+}
+
+func (s *requestChatHistorySpy) ListChats(context.Context, domainChat.ListChatsRequest) (domainChat.ListChatsResponse, error) {
+ return domainChat.ListChatsResponse{}, nil
+}
+
+func (s *requestChatHistorySpy) GetChatMessages(context.Context, domainChat.GetChatMessagesRequest) (domainChat.GetChatMessagesResponse, error) {
+ return domainChat.GetChatMessagesResponse{}, nil
+}
+
+func (s *requestChatHistorySpy) PinChat(context.Context, domainChat.PinChatRequest) (domainChat.PinChatResponse, error) {
+ return domainChat.PinChatResponse{}, nil
+}
+
+func (s *requestChatHistorySpy) SetDisappearingTimer(context.Context, domainChat.SetDisappearingTimerRequest) (domainChat.SetDisappearingTimerResponse, error) {
+ return domainChat.SetDisappearingTimerResponse{}, nil
+}
+
+func (s *requestChatHistorySpy) ArchiveChat(context.Context, domainChat.ArchiveChatRequest) (domainChat.ArchiveChatResponse, error) {
+ return domainChat.ArchiveChatResponse{}, nil
+}
+
+func (s *requestChatHistorySpy) RequestChatHistory(_ context.Context, request domainChat.RequestChatHistoryRequest) (domainChat.RequestChatHistoryResponse, error) {
+ s.calls++
+ s.lastRequest = request
+ return domainChat.RequestChatHistoryResponse{Status: "requested", ChatJID: request.ChatJID}, nil
+}
+
+// TestRequestChatHistoryAllowsEmptyBody pins the fix for Fiber v3.4.0's
+// Bind().Body() rejecting a bodyless request with no Content-Type: the
+// optional body must not require a Content-Type to fall back to defaults.
+func TestRequestChatHistoryAllowsEmptyBody(t *testing.T) {
+ app := fiber.New()
+ spy := &requestChatHistorySpy{}
+ controller := &Chat{Service: spy}
+ app.Post("/chat/:chat_jid/history", controller.RequestChatHistory)
+
+ req := httptest.NewRequest("POST", "/chat/6289685028129%40s.whatsapp.net/history", nil)
+
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ defer resp.Body.Close()
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ require.Equal(t, 1, spy.calls)
+ require.Equal(t, "[email protected]", spy.lastRequest.ChatJID)
+}
+
+// TestRequestChatHistoryIgnoresConflictingBodyChatJID pins the fix that the
+// route chat_jid is authoritative: a body chat_jid must never override the
+// storage lookup / history request target.
+func TestRequestChatHistoryIgnoresConflictingBodyChatJID(t *testing.T) {
+ app := fiber.New()
+ spy := &requestChatHistorySpy{}
+ controller := &Chat{Service: spy}
+ app.Post("/chat/:chat_jid/history", controller.RequestChatHistory)
+
+ body := `{"chat_jid":"[email protected]","count":50}`
+ req := httptest.NewRequest("POST", "/chat/6289685028129%40s.whatsapp.net/history", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ defer resp.Body.Close()
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ require.Equal(t, 1, spy.calls)
+ require.Equal(t, "[email protected]", spy.lastRequest.ChatJID)
+ require.Equal(t, 50, spy.lastRequest.Count)
+}
diff --git a/src/usecase/chat.go b/src/usecase/chat.go
index f5753273..d56fca60 100644
--- a/src/usecase/chat.go
+++ b/src/usecase/chat.go
@@ -13,6 +13,7 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/validations"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow/appstate"
+ "go.mau.fi/whatsmeow/types"
)
type serviceChat struct {
@@ -416,3 +417,85 @@ func (service serviceChat) ArchiveChat(ctx context.Context, request domainChat.A
return response, nil
}
+
+// RequestChatHistory asks the phone for older messages of a chat (what
+// WhatsApp Web does when you scroll up / "load older messages"). It anchors
+// the request at the oldest message currently stored for that chat and sends
+// a HISTORY_SYNC_ON_DEMAND peer message via whatsmeow's
+// BuildHistorySyncRequest. The phone answers asynchronously with a
+// *events.HistorySync (ON_DEMAND), which the existing history-sync handler
+// persists into chat storage the same way it does for the initial bootstrap.
+func (service serviceChat) RequestChatHistory(ctx context.Context, request domainChat.RequestChatHistoryRequest) (response domainChat.RequestChatHistoryResponse, err error) {
+ if err = validations.ValidateRequestChatHistory(ctx, &request); err != nil {
+ return response, err
+ }
+
+ deviceID := deviceIDFromContext(ctx)
+ if deviceID == "" {
+ return response, fmt.Errorf("device identification required")
+ }
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ // Resolve the anchor before touching the network: a chat with no stored
+ // messages has nothing for the phone to anchor an on-demand sync on, so
+ // fail fast on that instead of requiring a live connection first.
+ oldest, err := service.chatStorageRepo.GetOldestMessageByDevice(deviceID, request.ChatJID)
+ if err != nil {
+ logrus.WithError(err).WithField("chat_jid", request.ChatJID).Error("Failed to look up oldest stored message")
+ return response, err
+ }
+ if oldest == nil {
+ return response, pkgError.ValidationError("chat has no stored messages yet; nothing to anchor the history sync request on")
+ }
+
+ // Validate JID and ensure connection
+ targetJID, err := utils.ValidateJidWithLogin(client, request.ChatJID)
+ if err != nil {
+ return response, err
+ }
+
+ senderJID := targetJID
+ if parsed, parseErr := types.ParseJID(oldest.Sender); parseErr == nil {
+ senderJID = parsed
+ } else if oldest.IsFromMe && client.Store != nil && client.Store.ID != nil {
+ senderJID = client.Store.ID.ToNonAD()
+ }
+
+ anchor := &types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: targetJID,
+ Sender: senderJID,
+ IsFromMe: oldest.IsFromMe,
+ IsGroup: targetJID.Server == types.GroupServer,
+ },
+ ID: oldest.ID,
+ Timestamp: oldest.Timestamp,
+ }
+
+ historyRequest := client.BuildHistorySyncRequest(anchor, request.Count)
+ if _, err = client.SendPeerMessage(ctx, historyRequest); err != nil {
+ logrus.WithError(err).WithFields(logrus.Fields{
+ "chat_jid": request.ChatJID,
+ "count": request.Count,
+ }).Error("Failed to send on-demand history sync request")
+ return response, err
+ }
+
+ response.Status = "requested"
+ response.ChatJID = request.ChatJID
+ response.RequestedCount = request.Count
+ response.AnchorMessageID = oldest.ID
+ response.AnchorTimestamp = oldest.Timestamp.Format(time.RFC3339)
+
+ logrus.WithFields(logrus.Fields{
+ "chat_jid": request.ChatJID,
+ "requested_count": request.Count,
+ "anchor_message_id": oldest.ID,
+ }).Info("Requested on-demand chat history successfully")
+
+ return response, nil
+}
diff --git a/src/usecase/chat_test.go b/src/usecase/chat_test.go
index 931f4ff5..2634840c 100644
--- a/src/usecase/chat_test.go
+++ b/src/usecase/chat_test.go
@@ -9,6 +9,7 @@ import (
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"
+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/types"
@@ -371,11 +372,23 @@ 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
+ chat *domainChatStorage.Chat
+ chats []*domainChatStorage.Chat
+ messages []*domainChatStorage.Message
+ globalMessageCount int64
+ deviceMessageCounts map[string]int64
+ oldestMessage *domainChatStorage.Message
+ oldestMessageErr error
+ oldestMessageCalled bool
+ oldestMessageDeviceID string
+ oldestMessageChatJID string
+}
+
+func (r *chatUsecaseRepoStub) GetOldestMessageByDevice(deviceID, chatJID string) (*domainChatStorage.Message, error) {
+ r.oldestMessageCalled = true
+ r.oldestMessageDeviceID = deviceID
+ r.oldestMessageChatJID = chatJID
+ return r.oldestMessage, r.oldestMessageErr
}
func (r *chatUsecaseRepoStub) GetChatByDevice(_, _ string) (*domainChatStorage.Chat, error) {
@@ -440,3 +453,88 @@ func TestChatDisplayName(t *testing.T) {
})
}
}
+
+// TestRequestChatHistoryValidation pins the request-body validation (bad
+// chat_jid, out-of-range count) that RequestChatHistory delegates to
+// validations.ValidateRequestChatHistory before touching storage or the
+// network.
+func TestRequestChatHistoryValidation(t *testing.T) {
+ accountJID := types.NewJID("628999999999", types.DefaultUserServer)
+ deviceID := accountJID.String()
+ client := &whatsmeow.Client{Store: &store.Device{ID: &accountJID}}
+ repo := &chatUsecaseRepoStub{}
+ service := NewChatService(repo)
+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, client, nil))
+
+ _, err := service.RequestChatHistory(ctx, domainChat.RequestChatHistoryRequest{
+ ChatJID: "",
+ Count: 50,
+ })
+ if err == nil {
+ t.Fatal("expected validation error for empty chat_jid, got nil")
+ }
+ if repo.oldestMessageCalled {
+ t.Fatal("expected anchor lookup to be skipped when validation fails")
+ }
+
+ _, err = service.RequestChatHistory(ctx, domainChat.RequestChatHistoryRequest{
+ ChatJID: "[email protected]",
+ Count: 501,
+ })
+ if err == nil {
+ t.Fatal("expected validation error for count above cap, got nil")
+ }
+}
+
+// TestRequestChatHistoryRequiresClient mirrors the other chat mutation
+// usecases (PinChat/ArchiveChat): without a WhatsApp client in context, the
+// call must fail with ErrWaCLI instead of attempting anything else.
+func TestRequestChatHistoryRequiresClient(t *testing.T) {
+ deviceID := "[email protected]"
+ repo := &chatUsecaseRepoStub{}
+ service := NewChatService(repo)
+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, nil))
+
+ _, err := service.RequestChatHistory(ctx, domainChat.RequestChatHistoryRequest{
+ ChatJID: "[email protected]",
+ Count: 50,
+ })
+ if err != pkgError.ErrWaCLI {
+ t.Fatalf("expected ErrWaCLI, got %v", err)
+ }
+ if repo.oldestMessageCalled {
+ t.Fatal("expected anchor lookup to be skipped without a client")
+ }
+}
+
+// TestRequestChatHistoryNoStoredMessages pins the anchor-resolution rule: the
+// phone needs an oldest known message ID/timestamp to know where to start
+// looking for older history, so a chat with nothing stored yet must fail
+// validation instead of sending an unanchored request.
+func TestRequestChatHistoryNoStoredMessages(t *testing.T) {
+ accountJID := types.NewJID("628999999999", types.DefaultUserServer)
+ deviceID := accountJID.String()
+ client := &whatsmeow.Client{Store: &store.Device{ID: &accountJID}}
+ chatJID := "[email protected]"
+ repo := &chatUsecaseRepoStub{oldestMessage: nil}
+ service := NewChatService(repo)
+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, client, nil))
+
+ _, err := service.RequestChatHistory(ctx, domainChat.RequestChatHistoryRequest{
+ ChatJID: chatJID,
+ Count: 50,
+ })
+ if err == nil {
+ t.Fatal("expected error when chat has no stored messages, got nil")
+ }
+ if _, ok := err.(pkgError.ValidationError); !ok {
+ t.Fatalf("expected a ValidationError, got %T: %v", err, err)
+ }
+ if !repo.oldestMessageCalled {
+ t.Fatal("expected anchor lookup to be attempted")
+ }
+ if repo.oldestMessageDeviceID != deviceID || repo.oldestMessageChatJID != chatJID {
+ t.Fatalf("anchor lookup used device=%q chat=%q, want device=%q chat=%q",
+ repo.oldestMessageDeviceID, repo.oldestMessageChatJID, deviceID, chatJID)
+ }
+}
diff --git a/src/validations/chat_validation.go b/src/validations/chat_validation.go
index b2a4133b..4abe84e8 100644
--- a/src/validations/chat_validation.go
+++ b/src/validations/chat_validation.go
@@ -91,6 +91,28 @@ func validateTimerValue(value any) error {
return pkgError.ValidationError("timer_seconds must be one of: 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d)")
}
+// MaxRequestChatHistoryCount caps how many older messages can be requested
+// from the phone in a single on-demand history sync request.
+const MaxRequestChatHistoryCount = 500
+
+func ValidateRequestChatHistory(ctx context.Context, request *domainChat.RequestChatHistoryRequest) error {
+ // Set default count if not provided
+ if request.Count == 0 {
+ request.Count = 50
+ }
+
+ err := validation.ValidateStructWithContext(ctx, request,
+ validation.Field(&request.ChatJID, validation.Required),
+ validation.Field(&request.Count, validation.Min(1), validation.Max(MaxRequestChatHistoryCount)),
+ )
+
+ if err != nil {
+ return pkgError.ValidationError(err.Error())
+ }
+
+ return nil
+}
+
func ValidateArchiveChat(ctx context.Context, request *domainChat.ArchiveChatRequest) error {
err := validation.ValidateStructWithContext(ctx, request,
validation.Field(&request.ChatJID, validation.Required),
diff --git a/src/validations/chat_validation_test.go b/src/validations/chat_validation_test.go
index 57b66030..96aa01c2 100644
--- a/src/validations/chat_validation_test.go
+++ b/src/validations/chat_validation_test.go
@@ -250,3 +250,77 @@ func TestValidateSetDisappearingTimer(t *testing.T) {
})
}
}
+
+func TestValidateRequestChatHistory(t *testing.T) {
+ type args struct {
+ request domainChat.RequestChatHistoryRequest
+ }
+ tests := []struct {
+ name string
+ args args
+ err any
+ expectedCount int
+ }{
+ {
+ name: "should success with valid request",
+ args: args{request: domainChat.RequestChatHistoryRequest{
+ ChatJID: "[email protected]",
+ Count: 100,
+ }},
+ err: nil,
+ expectedCount: 100,
+ },
+ {
+ name: "should default count to 50 when zero",
+ args: args{request: domainChat.RequestChatHistoryRequest{
+ ChatJID: "[email protected]",
+ Count: 0,
+ }},
+ err: nil,
+ expectedCount: 50,
+ },
+ {
+ name: "should success with max count",
+ args: args{request: domainChat.RequestChatHistoryRequest{
+ ChatJID: "[email protected]",
+ Count: 500,
+ }},
+ err: nil,
+ expectedCount: 500,
+ },
+ {
+ name: "should error with empty chat_jid",
+ args: args{request: domainChat.RequestChatHistoryRequest{
+ ChatJID: "",
+ Count: 50,
+ }},
+ err: pkgError.ValidationError("chat_jid: cannot be blank."),
+ },
+ {
+ name: "should error with count above cap",
+ args: args{request: domainChat.RequestChatHistoryRequest{
+ ChatJID: "[email protected]",
+ Count: 501,
+ }},
+ err: pkgError.ValidationError("count: must be no greater than 500."),
+ },
+ {
+ name: "should error with negative count",
+ args: args{request: domainChat.RequestChatHistoryRequest{
+ ChatJID: "[email protected]",
+ Count: -1,
+ }},
+ err: pkgError.ValidationError("count: must be no less than 1."),
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ValidateRequestChatHistory(context.Background(), &tt.args.request)
+ assert.Equal(t, tt.err, err)
+ if tt.err == nil {
+ assert.Equal(t, tt.expectedCount, tt.args.request.Count)
+ }
+ })
+ }
+}