From 62fc4821c4a66313c300328aa1cf19808a41e0de Mon Sep 17 00:00:00 2001
From: Matthias Nott <mnott@mnsoft.org>
Date: Tue, 24 Mar 2026 09:41:36 +0100
Subject: [PATCH] fix: send catch_up on app resume to fetch messages missed during background

---
 lib/services/mqtt_service.dart |    9 +++++----
 lib/screens/chat_screen.dart   |    6 ++++++
 2 files changed, 11 insertions(+), 4 deletions(-)

diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart
index f8d360d..f6d7dd5 100644
--- a/lib/screens/chat_screen.dart
+++ b/lib/screens/chat_screen.dart
@@ -164,6 +164,12 @@
       _sendCommand('sync', activeId != null ? {'activeSessionId': activeId} : null);
       // catch_up is sent after sessions arrive (in _handleSessions)
     };
+    _ws!.onResume = () {
+      // App came back from background with connection still alive.
+      // Send catch_up to fetch any messages missed during suspend.
+      _chatLog('onResume: sending catch_up with lastSeq=$_lastSeq');
+      _sendCommand('catch_up', {'lastSeq': _lastSeq});
+    };
     _ws!.onError = (error) {
       debugPrint('MQTT error: $error');
     };
diff --git a/lib/services/mqtt_service.dart b/lib/services/mqtt_service.dart
index 1ff7a7d..e93e52b 100644
--- a/lib/services/mqtt_service.dart
+++ b/lib/services/mqtt_service.dart
@@ -56,6 +56,7 @@
   void Function()? onOpen;
   void Function()? onClose;
   void Function()? onReconnecting;
+  void Function()? onResume;
   void Function(String error)? onError;
 
   ConnectionStatus get status => _status;
@@ -524,10 +525,10 @@
           _setStatus(ConnectionStatus.reconnecting);
           connect();
         } else {
-          // Appears connected — just let it be. The MQTT keepalive will
-          // detect dead connections and auto-reconnect will handle it.
-          // Don't call onOpen (it resets sessionReady and causes flicker).
-          _mqttLog('MQTT: appears connected on resume, keeping current state');
+          // Appears connected — notify listener to fetch missed messages
+          // via catch_up. Don't call onOpen (it resets sessionReady and causes flicker).
+          _mqttLog('MQTT: appears connected on resume, triggering catch_up');
+          onResume?.call();
         }
       case AppLifecycleState.paused:
         break;

--
Gitblit v1.3.1