From 1bf6e76e31383aef77e42943fc2caf350cf7e096 Mon Sep 17 00:00:00 2001
From: Matthias Nott <mnott@mnsoft.org>
Date: Mon, 06 Apr 2026 13:35:05 +0200
Subject: [PATCH] fix: resume message reload, direct session writes, MQTT trace pipe to server

---
 lib/screens/chat_screen.dart |   39 ++++++++++++++++++---------------------
 1 files changed, 18 insertions(+), 21 deletions(-)

diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart
index 22efed5..e470ce7 100644
--- a/lib/screens/chat_screen.dart
+++ b/lib/screens/chat_screen.dart
@@ -65,6 +65,7 @@
   String? _playingMessageId;
   int _lastSeq = 0;
   bool _isCatchingUp = false;
+  bool _catchUpReceived = false;
   bool _screenshotForChat = false;
   // FIFO dedup queue: O(1) eviction by removing from front when over cap.
   final List<int> _seenSeqsList = [];
@@ -222,28 +223,20 @@
       // Re-register APNs token after reconnect so daemon always has a fresh token
       _push?.onMqttConnected();
     };
-    _ws!.onResume = () {
-      // App came back from background — connection may or may not be alive.
-      // Try catch_up first, but if no response comes, force reconnect.
-      _chatLog('onResume: sending catch_up with lastSeq=$_lastSeq');
-      final seqBefore = _lastSeq;
+    _ws!.onResume = () async {
+      // App came back from background — reload messages and catch up.
+      _chatLog('onResume: reloading messages and sending catch_up');
       _sendCommand('catch_up', {'lastSeq': _lastSeq});
-      // Force UI rebuild for any buffered messages
-      Future.delayed(const Duration(milliseconds: 300), () {
-        if (mounted) {
-          setState(() {});
-          _scrollToBottom();
-        }
-      });
-      // If catch_up didn't produce a response in 2s, connection is dead — reconnect
-      Future.delayed(const Duration(seconds: 2), () {
-        if (!mounted) return;
-        if (_lastSeq == seqBefore) {
-          // No new messages arrived — connection likely dead
-          _chatLog('onResume: no catch_up response after 2s, forcing reconnect');
-          _ws?.forceReconnect();
-        }
-      });
+      // Force reload current session messages from provider (triggers rebuild)
+      final activeId = ref.read(activeSessionIdProvider);
+      if (activeId != null) {
+        // Re-save then re-load to ensure UI matches persisted state
+        await ref.read(messagesProvider.notifier).switchSession(activeId);
+      }
+      if (mounted) {
+        setState(() {});
+        _scrollToBottom();
+      }
     };
     _ws!.onError = (error) {
       debugPrint('MQTT error: $error');
@@ -259,6 +252,9 @@
     );
 
     await _ws!.connect();
+
+    // Attach MQTT to trace service for auto-publishing logs to server
+    TraceService.instance.attachMqtt(_ws!);
 
     // Initialize push notifications after MQTT is set up so token can be
     // sent immediately if already connected.
@@ -371,6 +367,7 @@
         final sessionId = msg['sessionId'] as String?;
         if (sessionId != null) _incrementUnread(sessionId);
       case 'catch_up':
+        _catchUpReceived = true;
         final serverSeq = msg['serverSeq'] as int?;
         if (serverSeq != null) {
           // Always sync to server's seq — if server restarted, its seq may be lower

--
Gitblit v1.3.1