From f28cf788428c8ab4465e51c62b63fc038b8d2971 Mon Sep 17 00:00:00 2001
From: Matthias Nott <mnott@mnsoft.org>
Date: Sun, 05 Jul 2026 13:29:28 +0200
Subject: [PATCH] Refactor upgrade flow and add debug state request handling

---
 lib/services/mqtt_service.dart |   35 +++++++++++++++++++++++++++++++++++
 1 files changed, 35 insertions(+), 0 deletions(-)

diff --git a/lib/services/mqtt_service.dart b/lib/services/mqtt_service.dart
index 0718063..72632aa 100644
--- a/lib/services/mqtt_service.dart
+++ b/lib/services/mqtt_service.dart
@@ -81,6 +81,9 @@
   String? connectedHost; // The host we're currently connected to
   String? connectedVia; // "Local", "VPN", "Remote", "Bonjour", "Scan"
   void Function(Map<String, dynamic> message)? onMessage;
+  /// Called when the server sends a debug_state_request on pailot/control/out.
+  /// The handler should read current session state and call [publishDebugStateResponse].
+  void Function(String requestId)? onDebugStateRequest;
   void Function()? onOpen;
   void Function()? onClose;
   void Function()? onReconnecting;
@@ -625,6 +628,15 @@
 
     // pailot/control/out — command responses
     if (topic == 'pailot/control/out') {
+      // Intercept debug_state_request — handle locally, do not forward to UI.
+      if (json['type'] == 'debug_state_request') {
+        final requestId = json['requestId'] as String?;
+        if (requestId != null) {
+          _mqttLog('debug_state_request received (requestId=$requestId)');
+          onDebugStateRequest?.call(requestId);
+        }
+        return;
+      }
       onMessage?.call(json);
       return;
     }
@@ -686,6 +698,29 @@
     }
   }
 
+  /// Publish a debug_state_response back to the broker on pailot/control/in.
+  /// Call this from the [onDebugStateRequest] handler once session state is collected.
+  void publishDebugStateResponse({
+    required String requestId,
+    required String? activeSessionId,
+    required List<Map<String, dynamic>> sessions,
+    String? appVersion,
+    String? platform,
+  }) {
+    _publish('pailot/control/in', {
+      'msgId': const Uuid().v4(),
+      'type': 'command',
+      'command': 'debug_state_response',
+      'requestId': requestId,
+      'activeSessionId': activeSessionId,
+      'sessions': sessions,
+      if (appVersion != null) 'appVersion': appVersion,
+      if (platform != null) 'platform': platform,
+      'ts': DateTime.now().millisecondsSinceEpoch,
+    }, MqttQos.atLeastOnce);
+    _mqttLog('debug_state_response sent for requestId=$requestId sessions=${sessions.length}');
+  }
+
   /// Send a message — routes to the appropriate MQTT topic based on content.
   void send(Map<String, dynamic> message) {
     final type = message['type'] as String?;

--
Gitblit v1.3.1