Fix: fetchMessageHistory con evento SSE y logs de debug
All checks were successful
build-and-deploy / build-and-deploy (push) Successful in 1m9s

- Agregar logs detallados en /api/debug/history/fetch para diagnosticar
- Emitir evento SSE 'history.synced' cuando llegan mensajes del historial
- Frontend ahora escucha el evento SSE en vez de timeout fijo de 3 segundos
- Agregar script y documentación para referencia de Baileys message history
This commit is contained in:
2025-12-04 12:33:22 -06:00
parent a9e786a8bd
commit 32f66c8fe0
7 changed files with 2004 additions and 10 deletions

View File

@@ -395,10 +395,10 @@ const fetchWhatsAppHistory = async () => {
if (!selectedInstance.value?.value || !selectedChat.value) return
loadingWhatsAppHistory.value = true
try {
const instanceId = selectedInstance.value.value
const chatId = selectedChat.value.id
const instanceId = selectedInstance.value.value
const chatId = selectedChat.value.id
try {
// Get the oldest message from local DB
const oldest = await $fetch<{
hasMessages: boolean
@@ -406,6 +406,23 @@ const fetchWhatsAppHistory = async () => {
timestamp: number | null
}>(`/api/messages/${instanceId}/${chatId}/oldest`)
// Create a promise that resolves when history.synced event arrives
const historyPromise = new Promise<{ messagesCount: number; timeout?: boolean }>((resolve) => {
// Set up listener for history.synced event
const cleanup = on('history.synced', (data) => {
if (data.instanceId === instanceId) {
cleanup() // Remove listener
resolve({ messagesCount: data.messagesCount })
}
})
// Timeout de seguridad (15 segundos)
setTimeout(() => {
cleanup() // Remove listener
resolve({ messagesCount: 0, timeout: true })
}, 15000)
})
// Request history from WhatsApp
if (!oldest.hasMessages) {
// No messages in DB, request without reference
@@ -429,10 +446,18 @@ const fetchWhatsAppHistory = async () => {
})
}
// Wait for history sync to complete and reload
await new Promise(r => setTimeout(r, 3000))
await reloadMessages()
hasMoreMessages.value = true
// Wait for history sync event or timeout
const result = await historyPromise
if (result.timeout) {
console.log('[History] Timeout waiting for history sync - WhatsApp may not have more messages')
} else if (result.messagesCount > 0) {
console.log(`[History] Received ${result.messagesCount} messages from history sync`)
await reloadMessages()
hasMoreMessages.value = true
} else {
console.log('[History] No messages received from history sync')
}
} catch (e) {
console.error('Error fetching WhatsApp history:', e)
} finally {