From 34b82ffb9b31866b528cd91a3d2ec360dbb8da5e Mon Sep 17 00:00:00 2001
From: Matthias Nott <mnott@mnsoft.org>
Date: Mon, 06 Apr 2026 13:05:50 +0200
Subject: [PATCH] fix: explicit per-session MQTT subscriptions, lifecycle observer, resume reconnect with fallback
---
lib/screens/chat_screen.dart | 25 ++++++++++++++++++++++---
1 files changed, 22 insertions(+), 3 deletions(-)
diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart
index 9b8a551..22efed5 100644
--- a/lib/screens/chat_screen.dart
+++ b/lib/screens/chat_screen.dart
@@ -223,10 +223,27 @@
_push?.onMqttConnected();
};
_ws!.onResume = () {
- // App came back from background with connection still alive.
- // Send catch_up to fetch any messages missed during suspend.
+ // 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;
_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();
+ }
+ });
};
_ws!.onError = (error) {
debugPrint('MQTT error: $error');
@@ -247,7 +264,9 @@
// sent immediately if already connected.
_push = PushService(mqttService: _ws!);
_push!.onNotificationTap = (data) {
- // If notification carried a sessionId, switch to that session
+ // Switch to the session immediately, then request catch_up.
+ // The MQTT connection auto-reconnects on resume, and onResume
+ // already sends catch_up. We just need to be on the right session.
final sessionId = data['sessionId'] as String?;
if (sessionId != null && mounted) {
_switchSession(sessionId);
--
Gitblit v1.3.1