Modern Apps git

← Modern-Apps.git

messages: whatsapp: fix crash on backoff

Commit
f6dee6f69d9b15c279d09095792dc953e0fdd9fb
Author
Vayun Mathur <[email protected]>
When
2026-07-16 18:56 UTC (4 months ago)
Parents
c4682ce

Diff

messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.ktindex 7ed628af8d..b85bb264f2 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt@@ -794,6 +794,7 @@ object MessagesSessionManager {         GVoiceClient.forceResync()         TelegramClient.forceResync()         SignalClient.forceResync()+        com.vayunmathur.messages.whatsapp.WhatsAppClient.forceResync()     }      fun fetchMessages(conversationId: String) {@@ -879,6 +880,10 @@ object MessagesSessionManager {     }      private suspend fun handleEvent(event: GMEvent) {+        // Never let a single bad event crash the whole app: this pipeline persists to Room, and a+        // malformed/edge-case event would otherwise take down the process and crash-loop on replay+        // of the offline queue. Log and skip instead.+        try {         when (event) {             is GMEvent.ConversationUpdate -> {                 val id = "${event.source.idPrefix}:${event.conversationId}"@@ -916,6 +921,26 @@ object MessagesSessionManager {             is GMEvent.MessageUpdate -> {                 val convId = "${event.source.idPrefix}:${event.conversationId}"                 val msgId = "${event.source.idPrefix}:${event.messageId}"+                // Ensure the parent conversation row exists before inserting the message (the+                // messages table FKs to it). Unlike IncomingMessage, a MessageUpdate is NOT preceded+                // by a guaranteed ConversationUpdate — e.g. own messages synced from another linked+                // device (fromMe), or history backfill for a chat not yet persisted — so without+                // this the insert throws SQLiteConstraintException and crashes the app. Preview is+                // refreshed but unread is NOT bumped (these are backfill / outgoing, not new unread).+                val existingConv = db.conversationDao().get(convId)+                db.conversationDao().upsert(+                    existingConv?.copy(+                        lastMessagePreview = event.body.ifEmpty { existingConv.lastMessagePreview },+                    ) ?: Conversation(+                        id = convId,+                        source = event.source,+                        peerName = null,+                        peerPhoneE164 = null,+                        avatarUrl = null,+                        lastMessagePreview = event.body,+                        unreadCount = 0,+                    )+                )                 db.messageDao().upsert(                     Message(                         id = msgId,@@ -1062,6 +1087,9 @@ object MessagesSessionManager {             }             else -> Unit         }+        } catch (e: Exception) {+            Log.e(TAG, "handleEvent failed for ${event::class.simpleName}", e)+        }     }      private fun sourceFor(conversationId: String): MessageSource? = when {
messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.ktindex d2e9ae32c7..127746f727 100644--- a/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppClient.kt@@ -207,6 +207,32 @@ object WhatsAppClient {         _state.value = State.NeedsSetup     } +    /**+     * User-triggered "force resync" (settings button): drop any existing socket and reconnect from+     * scratch, regardless of current state. This is the recovery path when the socket has silently+     * died — resetting attempts and calling connect() (which tears down the old socket first).+     * No-op if there is no saved session.+     */+    fun forceResync() {+        if (!initialized.get()) return+        val auth = authData ?: run {+            WhatsAppDiag.log(TAG, "forceResync: no session, ignoring")+            return+        }+        WhatsAppDiag.log(TAG, "forceResync: forcing full reconnect")+        reconnectAttempts = 0+        reconnectJob?.cancel()+        suppressReconnect = false+        scope.launch {+            try {+                connect(auth)+            } catch (e: Exception) {+                Log.e(TAG, "forceResync connect failed", e)+                scheduleReconnect()+            }+        }+    }+     private fun scheduleReconnect() {         // Never permanently give up: a companion device must keep retrying so it recovers after a         // long offline stretch (device asleep, no Wi-Fi/data) without a manual app restart. The@@ -929,8 +955,13 @@ object WhatsAppClient {                     }                 } -                // Ack messages, notifications, and receipts (whatsmeow/receipt.go)-                if (node.tag == "message" || node.tag == "notification" || node.tag == "receipt") {+                // Ack messages, notifications, receipts AND calls (whatsmeow/receipt.go ++                // call.go). Calls MUST be acked too: during the post-login offline flush the server+                // is flow-controlled and head-of-line — if the offline <call> offers aren't acked it+                // stops delivering, so queued <message> stanzas never arrive ("stuck syncing").+                if (node.tag == "message" || node.tag == "notification" ||+                    node.tag == "receipt" || node.tag == "call"+                ) {                     val ack = WhatsAppProtocol.buildAck(                         nodeClass = node.tag,                         nodeId = node.attrs["id"] ?: "",