From 4a25f718a8ae4b05368788d2ea55f82c4b71a4f8 Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Sun, 13 Sep 2026 12:30:51 +0200 Subject: [PATCH 01/10] Close USB serial port off the UI isolate close(2) on a tty whose output the peer never drained blocks in the kernel for the line discipline's closing_wait (measured 30.4s on Linux against a CDC-ACM device that never reads its bulk OUT endpoint, e.g. a MeshCore board flashed with a BLE-only companion build). FlSerial's closePort() is a synchronous FFI call, so the whole app froze for that window on every failed USB connect and on disconnect. fl_close() only touches process-global native state, so run it through Isolate.run() and replicate the Dart-side cleanup closePort() does (stream close, calloc'd I/O buffers, flh reset). Log when the close exceeds 1s so the "device is not draining" case is visible in the debug log. Verified against the wedged device: inline close blocked the calling isolate for 30476ms with 0 timer ticks; the isolate close took 30302ms with 302 ticks, i.e. the main isolate stayed responsive throughout. --- lib/services/usb_serial_service_native.dart | 55 ++++++++++++++++++++- pubspec.yaml | 1 + 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index 1976de94..376f1c7e 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -1,6 +1,9 @@ import 'dart:async'; +import 'dart:ffi'; import 'dart:io'; +import 'dart:isolate'; +import 'package:ffi/ffi.dart'; import 'package:flserial/flserial.dart'; import 'package:flserial/flserial_exception.dart'; import 'package:flutter/foundation.dart'; @@ -322,11 +325,13 @@ class UsbSerialService { try { if (serial?.isOpen() == FlOpenStatus.open) { serial?.setDTR(false); - serial?.closePort(); } } catch (_) { // Ignore errors while closing. } + if (serial != null) { + await _closePortOffUiIsolate(serial); + } // Note: we do NOT call free() here; that would globally reset native // state for all ports. The global reset is done in connect() instead, // before the next open, which is the safer place to do it. @@ -362,6 +367,54 @@ class UsbSerialService { ); } + /// Closes the native port without blocking the Dart UI isolate. + /// + /// `close(2)` on a tty whose output has not been drained by the peer blocks + /// in the kernel for the line discipline's `closing_wait` (30s by default — + /// measured 30.4s on Linux with a CDC-ACM device that never reads its bulk + /// OUT endpoint, e.g. a MeshCore board flashed with a BLE-only companion + /// build). `FlSerial.closePort()` is a synchronous FFI call, so running it + /// inline freezes the whole app for that entire window. `fl_close()` only + /// touches process-global native state, so it is safe to run in a helper + /// isolate; the Dart-side cleanup that `closePort()` also performs is + /// replicated here afterwards. + Future _closePortOffUiIsolate(FlSerial serial) async { + final flh = serial.flh; + serial.flh = -1; + if (flh >= 0) { + final startedAt = DateTime.now(); + try { + await Isolate.run(() => bindings.fl_close(flh)); + } catch (error) { + _debugLogService?.warn( + 'Native USB port close failed: $error', + tag: 'USB Serial', + ); + } + final elapsed = DateTime.now().difference(startedAt); + if (elapsed > const Duration(seconds: 1)) { + _debugLogService?.warn( + 'Native USB port close took ${elapsed.inMilliseconds}ms — the device ' + 'was not draining its serial input', + tag: 'USB Serial', + ); + } + } + try { + await serial.onSerialData.close(); + if (serial.serialReadBuff.address != 0) { + calloc.free(serial.serialReadBuff); + serial.serialReadBuff = Pointer.fromAddress(0); + } + if (serial.serialWriteBuff.address != 0) { + calloc.free(serial.serialWriteBuff); + serial.serialWriteBuff = Pointer.fromAddress(0); + } + } catch (_) { + // Ignore errors while releasing Dart-side resources. + } + } + void dispose() { // Synchronously close the native port so the SerialThread exits before // the Dart isolate is torn down (e.g. on hot restart). The async diff --git a/pubspec.yaml b/pubspec.yaml index 640acdb8..01608a39 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -43,6 +43,7 @@ dependencies: git: url: https://github.com/MeshEnvy/flserial.git ref: 48216310061efc8d5d217cc18014fc2cb501646e + ffi: ^2.1.3 # calloc.free for flserial's native I/O buffers provider: ^6.1.5+1 shared_preferences: ^2.2.2 uuid: ^4.3.3 From 9a90d1f44874b46296a6487e8bc75e11afa4ee8f Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Sun, 13 Sep 2026 12:50:06 +0200 Subject: [PATCH 02/10] Coordinate dispose() with the off-isolate close MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up: - dispose() now takes ownership of the FlSerial (nulls _serial) and clears serialReadBuff/serialWriteBuff after the synchronous closePort(); flserial frees those buffers but leaves the pointer fields dangling, so a later disconnect() reaching _closePortOffUiIsolate() with the same object would have freed them a second time. _closePortOffUiIsolate() additionally returns early when flh is already -1. - dispose() skips its synchronous close when a close is already in flight: fl_close() sets breakThread and joins the SerialThread before it reaches the blocking ::close(), so the thread — and its NativeCallable — is already gone while the helper isolate waits out closing_wait. The in-flight future is tracked in _pendingNativeClose. - If Isolate.run itself fails the port is now closed inline rather than leaking a native slot and SerialThread with no reachable handle. --- lib/services/usb_serial_service_native.dart | 75 +++++++++++++++------ 1 file changed, 54 insertions(+), 21 deletions(-) diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index 376f1c7e..9de3ab6f 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -35,6 +35,8 @@ class UsbSerialService { String? _connectedPortKey; String? _connectedPortLabel; FlSerial? _serial; + /// Non-null while the native port is being closed in a helper isolate. + Future? _pendingNativeClose; AppDebugLogService? _debugLogService; Object? _lastError; @@ -330,7 +332,15 @@ class UsbSerialService { // Ignore errors while closing. } if (serial != null) { - await _closePortOffUiIsolate(serial); + final pending = _closePortOffUiIsolate(serial); + _pendingNativeClose = pending; + try { + await pending; + } finally { + if (identical(_pendingNativeClose, pending)) { + _pendingNativeClose = null; + } + } } // Note: we do NOT call free() here; that would globally reset native // state for all ports. The global reset is done in connect() instead, @@ -380,26 +390,38 @@ class UsbSerialService { /// replicated here afterwards. Future _closePortOffUiIsolate(FlSerial serial) async { final flh = serial.flh; + if (flh < 0) { + // Already closed synchronously by dispose(); `closePort()` freed the + // native slot, the stream and both I/O buffers. Touching them again + // would double-free the calloc'd buffers. + return; + } serial.flh = -1; - if (flh >= 0) { - final startedAt = DateTime.now(); + final startedAt = DateTime.now(); + try { + await Isolate.run(() => bindings.fl_close(flh)); + } catch (error) { + // Spawning the helper failed, so the native slot and its SerialThread + // are still alive with no reachable handle. Close it inline instead — + // that blocks, but only in this already-degraded path. + _debugLogService?.warn( + 'Off-isolate USB port close failed ($error); closing inline', + tag: 'USB Serial', + ); try { - await Isolate.run(() => bindings.fl_close(flh)); - } catch (error) { - _debugLogService?.warn( - 'Native USB port close failed: $error', - tag: 'USB Serial', - ); - } - final elapsed = DateTime.now().difference(startedAt); - if (elapsed > const Duration(seconds: 1)) { - _debugLogService?.warn( - 'Native USB port close took ${elapsed.inMilliseconds}ms — the device ' - 'was not draining its serial input', - tag: 'USB Serial', - ); + bindings.fl_close(flh); + } catch (_) { + // Ignore errors while closing. } } + final elapsed = DateTime.now().difference(startedAt); + if (elapsed > const Duration(seconds: 1)) { + _debugLogService?.warn( + 'Native USB port close took ${elapsed.inMilliseconds}ms — the device ' + 'was not draining its serial input', + tag: 'USB Serial', + ); + } try { await serial.onSerialData.close(); if (serial.serialReadBuff.address != 0) { @@ -421,14 +443,25 @@ class UsbSerialService { // disconnect() path via unawaited() offers no ordering guarantee — the // isolate may die before the Future resolves, leaving the thread alive // with a dangling NativeCallable pointer. - if (_useDesktopFlSerial) { + // + // When a close is already in flight there is nothing left to do + // synchronously: `fl_close()` sets `breakThread` and joins the + // SerialThread *before* it reaches the blocking `::close()`, so the + // thread — and with it the NativeCallable — is already gone while the + // helper isolate waits out the kernel's closing_wait. + if (_useDesktopFlSerial && _pendingNativeClose == null) { final serial = _serial; + _serial = null; try { - if (serial?.isOpen() == FlOpenStatus.open) { - serial?.setDTR(false); - serial?.closePort(); // synchronous C call — kills the SerialThread + if (serial != null && serial.isOpen() == FlOpenStatus.open) { + serial.setDTR(false); + serial.closePort(); // synchronous C call — kills the SerialThread } } catch (_) {} + // closePort() frees both I/O buffers but leaves the pointer fields + // dangling; clear them so nothing can free them a second time. + serial?.serialReadBuff = Pointer.fromAddress(0); + serial?.serialWriteBuff = Pointer.fromAddress(0); } // Kick off the full async teardown for anything else (subscription cancel, // stream controller close). These are best-effort at dispose time. From b0b50168069209816a5ae45cae7e90d11730ab95 Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Sun, 13 Sep 2026 13:01:16 +0200 Subject: [PATCH 03/10] Serialize reconnect and teardown around the pending close Second review round: - connect() awaits _pendingNativeClose before touching flserial's global slot table. fl_close() (helper isolate) and fl_free()/fl_init() mutate the same flserial_tab, so reconnecting during the kernel's closing_wait could double-close the old slot or kill the freshly opened one. - dispose() no longer re-enters disconnect() when a close is in flight; the running disconnect owns the ordering (native close, then subscription cancel), so dispose only chains _closeFrameController onto the pending close. - dispose() frees the I/O buffers through the new _releaseSerialBuffers() on every path, not just after a successful closePort(); with _serial nulled, an error/closed-state dispose used to leak both 8 KiB buffers. - _handleSerialData() ignores callbacks once the status leaves `connected`: a callback queued before flh was invalidated made readList() throw and published a spurious transport error mid-teardown. --- lib/services/usb_serial_service_native.dart | 73 ++++++++++++++++----- 1 file changed, 56 insertions(+), 17 deletions(-) diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index 9de3ab6f..64a2eada 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -162,6 +162,24 @@ class UsbSerialService { // // This must happen before we register any new NativeCallable, so it must // be the very first thing we do in the desktop branch. + // A previous close may still be running in its helper isolate (the + // kernel can hold close(2) for closing_wait). fl_close() and fl_free() + // mutate the same process-global flserial_tab, so opening — and + // especially resetting — the table now would race the helper and could + // double-close the old slot or kill the freshly opened one. + final pendingClose = _pendingNativeClose; + if (pendingClose != null) { + _debugLogService?.info( + 'Waiting for the previous USB port close to finish before reopening', + tag: 'USB Serial', + ); + try { + await pendingClose; + } catch (_) { + // Failures are already logged by the close path. + } + } + try { bindings.fl_free(); bindings.fl_init(16); @@ -424,6 +442,17 @@ class UsbSerialService { } try { await serial.onSerialData.close(); + } catch (_) { + // Ignore errors while releasing Dart-side resources. + } + _releaseSerialBuffers(serial); + } + + /// Frees the two calloc'd I/O buffers `openPort()` allocated and clears the + /// pointer fields. `FlSerial.closePort()` frees them too but leaves the + /// fields dangling, so clearing is what makes a second release safe. + void _releaseSerialBuffers(FlSerial serial) { + try { if (serial.serialReadBuff.address != 0) { calloc.free(serial.serialReadBuff); serial.serialReadBuff = Pointer.fromAddress(0); @@ -443,25 +472,29 @@ class UsbSerialService { // disconnect() path via unawaited() offers no ordering guarantee — the // isolate may die before the Future resolves, leaving the thread alive // with a dangling NativeCallable pointer. - // - // When a close is already in flight there is nothing left to do - // synchronously: `fl_close()` sets `breakThread` and joins the - // SerialThread *before* it reaches the blocking `::close()`, so the - // thread — and with it the NativeCallable — is already gone while the - // helper isolate waits out the kernel's closing_wait. - if (_useDesktopFlSerial && _pendingNativeClose == null) { + final pendingClose = _pendingNativeClose; + if (pendingClose != null) { + // A disconnect is already running and owns the teardown ordering + // (native close first, subscription cancel after). Re-entering + // disconnect() here would cancel the subscription underneath it, so + // only chain the frame-controller cleanup onto that close. + unawaited(pendingClose.whenComplete(_closeFrameController)); + return; + } + if (_useDesktopFlSerial) { final serial = _serial; _serial = null; - try { - if (serial != null && serial.isOpen() == FlOpenStatus.open) { - serial.setDTR(false); - serial.closePort(); // synchronous C call — kills the SerialThread - } - } catch (_) {} - // closePort() frees both I/O buffers but leaves the pointer fields - // dangling; clear them so nothing can free them a second time. - serial?.serialReadBuff = Pointer.fromAddress(0); - serial?.serialWriteBuff = Pointer.fromAddress(0); + if (serial != null) { + try { + if (serial.isOpen() == FlOpenStatus.open) { + serial.setDTR(false); + serial.closePort(); // synchronous C call — kills the SerialThread + } + } catch (_) {} + // Free (or, after closePort(), just clear) the I/O buffers here: + // _serial is gone, so the disconnect() below can no longer reach them. + _releaseSerialBuffers(serial); + } } // Kick off the full async teardown for anything else (subscription cancel, // stream controller close). These are best-effort at dispose time. @@ -469,6 +502,12 @@ class UsbSerialService { } void _handleSerialData(FlSerialEventArgs event) { + if (_status != UsbSerialStatus.connected) { + // Teardown already invalidated the native handle; a callback queued + // before that would make readList() throw and publish a spurious + // transport error that triggers another disconnect. + return; + } try { final bytes = event.serial.readList(); if (bytes.isNotEmpty) { From 10f557e81155449827084bbb6b79ac70cde03f63 Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Sun, 13 Sep 2026 13:12:35 +0200 Subject: [PATCH 04/10] Serialize reconnect against the whole disconnect teardown Third review round: - disconnect() is now a re-entrant-safe wrapper around _disconnectInternal() whose future is held in _activeDisconnect for the entire teardown, not just the native close. connect() and dispose() wait on that instead of _pendingNativeClose, so a reconnect can no longer open a new port and then have the tail of the old teardown mark it disconnected. - dispose() closes on any live handle (flh >= 0) instead of only when isOpen() reports `open`: flserial keeps a valid slot and a running SerialThread in the I/O error state, which would otherwise have been orphaned. A setDTR() failure no longer skips the close. - _releaseSerialBuffers() takes alreadyFreed: closePort() frees both buffers but leaves the pointer fields dangling, so after a successful synchronous close the fields are only cleared, never freed a second time. Builds: flutter build linux --debug succeeds (after patching the unrelated glibc >= 2.42 / tinycthread once_flag clash in the flserial checkout). --- lib/services/usb_serial_service_native.dart | 104 ++++++++++++-------- 1 file changed, 63 insertions(+), 41 deletions(-) diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index 64a2eada..2a0e7526 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -35,8 +35,9 @@ class UsbSerialService { String? _connectedPortKey; String? _connectedPortLabel; FlSerial? _serial; - /// Non-null while the native port is being closed in a helper isolate. - Future? _pendingNativeClose; + /// Non-null while a disconnect teardown (native close in a helper isolate, + /// then subscription cancel) is running. + Future? _activeDisconnect; AppDebugLogService? _debugLogService; Object? _lastError; @@ -162,21 +163,22 @@ class UsbSerialService { // // This must happen before we register any new NativeCallable, so it must // be the very first thing we do in the desktop branch. - // A previous close may still be running in its helper isolate (the - // kernel can hold close(2) for closing_wait). fl_close() and fl_free() - // mutate the same process-global flserial_tab, so opening — and - // especially resetting — the table now would race the helper and could - // double-close the old slot or kill the freshly opened one. - final pendingClose = _pendingNativeClose; - if (pendingClose != null) { + // A previous disconnect may still be running: its native close waits out + // the kernel's closing_wait in a helper isolate, and it only marks the + // transport disconnected afterwards. fl_close() and fl_free() mutate the + // same process-global flserial_tab, so reopening now could race the + // helper, and the old teardown could later overwrite the new connection + // state. Wait for the whole teardown, not just the native close. + final pendingDisconnect = _activeDisconnect; + if (pendingDisconnect != null) { _debugLogService?.info( - 'Waiting for the previous USB port close to finish before reopening', + 'Waiting for the previous USB disconnect to finish before reopening', tag: 'USB Serial', ); try { - await pendingClose; + await pendingDisconnect; } catch (_) { - // Failures are already logged by the close path. + // Failures are already logged by the teardown path. } } @@ -312,8 +314,23 @@ class UsbSerialService { } } - Future disconnect() async { - if (_status == UsbSerialStatus.disconnected) return; + /// Tears the transport down. Re-entrant calls (e.g. the `onDone` handler + /// firing while a disconnect is already running) join the in-flight + /// teardown instead of racing it. + Future disconnect() { + final pending = _activeDisconnect; + if (pending != null) return pending; + if (_status == UsbSerialStatus.disconnected) return Future.value(); + final teardown = _disconnectInternal(); + _activeDisconnect = teardown; + return teardown.whenComplete(() { + if (identical(_activeDisconnect, teardown)) { + _activeDisconnect = null; + } + }); + } + + Future _disconnectInternal() async { final portLabel = _connectedPortLabel ?? _connectedPortKey; _debugLogService?.info( @@ -350,15 +367,7 @@ class UsbSerialService { // Ignore errors while closing. } if (serial != null) { - final pending = _closePortOffUiIsolate(serial); - _pendingNativeClose = pending; - try { - await pending; - } finally { - if (identical(_pendingNativeClose, pending)) { - _pendingNativeClose = null; - } - } + await _closePortOffUiIsolate(serial); } // Note: we do NOT call free() here; that would globally reset native // state for all ports. The global reset is done in connect() instead, @@ -449,18 +458,21 @@ class UsbSerialService { } /// Frees the two calloc'd I/O buffers `openPort()` allocated and clears the - /// pointer fields. `FlSerial.closePort()` frees them too but leaves the - /// fields dangling, so clearing is what makes a second release safe. - void _releaseSerialBuffers(FlSerial serial) { + /// pointer fields. + /// + /// [alreadyFreed] is set when `FlSerial.closePort()` ran: it frees both + /// buffers itself but leaves the pointer fields dangling, so they must only + /// be cleared, never freed again. + void _releaseSerialBuffers(FlSerial serial, {bool alreadyFreed = false}) { try { - if (serial.serialReadBuff.address != 0) { + if (!alreadyFreed && serial.serialReadBuff.address != 0) { calloc.free(serial.serialReadBuff); - serial.serialReadBuff = Pointer.fromAddress(0); } - if (serial.serialWriteBuff.address != 0) { + serial.serialReadBuff = Pointer.fromAddress(0); + if (!alreadyFreed && serial.serialWriteBuff.address != 0) { calloc.free(serial.serialWriteBuff); - serial.serialWriteBuff = Pointer.fromAddress(0); } + serial.serialWriteBuff = Pointer.fromAddress(0); } catch (_) { // Ignore errors while releasing Dart-side resources. } @@ -472,28 +484,38 @@ class UsbSerialService { // disconnect() path via unawaited() offers no ordering guarantee — the // isolate may die before the Future resolves, leaving the thread alive // with a dangling NativeCallable pointer. - final pendingClose = _pendingNativeClose; - if (pendingClose != null) { + final pendingDisconnect = _activeDisconnect; + if (pendingDisconnect != null) { // A disconnect is already running and owns the teardown ordering // (native close first, subscription cancel after). Re-entering // disconnect() here would cancel the subscription underneath it, so - // only chain the frame-controller cleanup onto that close. - unawaited(pendingClose.whenComplete(_closeFrameController)); + // only chain the frame-controller cleanup onto that teardown. + unawaited(pendingDisconnect.whenComplete(_closeFrameController)); return; } if (_useDesktopFlSerial) { final serial = _serial; _serial = null; if (serial != null) { - try { - if (serial.isOpen() == FlOpenStatus.open) { + // Close on any live handle, not only when isOpen() reports `open`: + // flserial keeps a valid slot (and a running SerialThread) when the + // port is in an I/O error state, and _serial is already unreachable. + var closed = false; + if (serial.flh >= 0) { + try { serial.setDTR(false); - serial.closePort(); // synchronous C call — kills the SerialThread + } catch (_) { + // Line-control failure must not skip the close below. } - } catch (_) {} - // Free (or, after closePort(), just clear) the I/O buffers here: - // _serial is gone, so the disconnect() below can no longer reach them. - _releaseSerialBuffers(serial); + try { + serial.closePort(); // synchronous C call — kills the SerialThread + closed = true; + } catch (_) {} + } + // _serial is gone, so the disconnect() below can no longer reach the + // buffers: release them here, or just clear the dangling pointers if + // closePort() already freed them. + _releaseSerialBuffers(serial, alreadyFreed: closed); } } // Kick off the full async teardown for anything else (subscription cancel, From fb7958a52e81f4902d262c3d8ea04273e13e662a Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Sun, 13 Sep 2026 15:33:44 +0200 Subject: [PATCH 05/10] Serialize connects against the connector-level teardown Fourth review round: - UsbSerialService.connect() now waits for _activeDisconnect before it claims the `connecting` status, covering the Android USB-host path too; previously the wait sat inside the desktop branch, so an Android reconnect could still be overwritten by the old teardown. - MeshCoreConnector.disconnect() is now a re-entrant-safe wrapper around _disconnectInternal() that publishes the teardown as _activeDisconnect, and connect()/connectUsb()/connectTcp() join it before starting. The transport-level guard alone could not prevent the connector's own teardown tail from setting the state back to `disconnected` after a new connection was up. Repeat disconnect() calls now join the in-flight teardown instead of returning early while it is still running. flutter analyze clean; flutter test 570 passing, 2 pre-existing failures in message_url_image_helper_test.dart (identical on a stashed tree); flutter build linux --debug succeeds. --- lib/connector/meshcore_connector.dart | 47 ++++++++++++++++++++- lib/services/usb_serial_service_native.dart | 39 +++++++++-------- 2 files changed, 67 insertions(+), 19 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 37198761..25046783 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -188,6 +188,12 @@ class MeshCoreConnector extends ChangeNotifier { String? _lastDeviceId; String? _lastDeviceDisplayName; bool _manualDisconnect = false; + /// Non-null while [disconnect] is tearing the transport down. Connect paths + /// join it so a teardown cannot finish after a new connection and reset the + /// state to `disconnected`. USB made this reachable: its native close now + /// waits out the kernel's closing_wait off the UI isolate, so the teardown + /// can outlive the tap that starts the next connection. + Future? _activeDisconnect; final MeshCoreUsbManager _usbManager = MeshCoreUsbManager(); final LinuxBlePairingService _linuxBlePairingService = LinuxBlePairingService(); @@ -1763,6 +1769,8 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'USB', ); + await _awaitActiveDisconnect(); + await stopScan(); _cancelReconnectTimer(); _manualDisconnect = false; @@ -1860,6 +1868,8 @@ class MeshCoreConnector extends ChangeNotifier { _appDebugLogService?.info('connectTcp: endpoint=$host:$port', tag: 'TCP'); + await _awaitActiveDisconnect(); + await stopScan(); _cancelReconnectTimer(); _manualDisconnect = false; @@ -2008,6 +2018,8 @@ class MeshCoreConnector extends ChangeNotifier { return; } + await _awaitActiveDisconnect(); + _activeTransport = MeshCoreTransportType.bluetooth; await stopScan(); @@ -2747,8 +2759,41 @@ class MeshCoreConnector extends ChangeNotifier { Future disconnect({ bool manual = true, bool skipBleDeviceDisconnect = false, + }) { + final inFlight = _activeDisconnect; + if (inFlight != null) return inFlight; + final teardown = _disconnectInternal( + manual: manual, + skipBleDeviceDisconnect: skipBleDeviceDisconnect, + ); + _activeDisconnect = teardown; + return teardown.whenComplete(() { + if (identical(_activeDisconnect, teardown)) { + _activeDisconnect = null; + } + }); + } + + /// Joins an in-flight [disconnect] so a new connection cannot be started + /// while the previous teardown is still running. + Future _awaitActiveDisconnect() async { + final pending = _activeDisconnect; + if (pending == null) return; + _appDebugLogService?.info( + 'Waiting for the in-flight disconnect to finish before connecting', + tag: 'Connection', + ); + try { + await pending; + } catch (_) { + // Teardown failures are logged by the disconnect path. + } + } + + Future _disconnectInternal({ + required bool manual, + required bool skipBleDeviceDisconnect, }) async { - if (_state == MeshCoreConnectionState.disconnecting) return; final transportAtDisconnect = _activeTransport; final transportLabel = switch (transportAtDisconnect) { MeshCoreTransportType.bluetooth => 'BLE', diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index 2a0e7526..781dfcb9 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -126,6 +126,26 @@ class UsbSerialService { throw UnsupportedError('USB serial is not supported on this platform.'); } + // A previous disconnect may still be running: on desktop its native close + // waits out the kernel's closing_wait in a helper isolate, and the + // teardown only marks the transport disconnected afterwards. Reopening + // before it finishes would let the old teardown overwrite the new + // connection's state (and, on desktop, race fl_free()/fl_close() over the + // process-global flserial_tab). Wait for the whole teardown — on every + // platform — before claiming the `connecting` state. + final pendingDisconnect = _activeDisconnect; + if (pendingDisconnect != null) { + _debugLogService?.info( + 'Waiting for the previous USB disconnect to finish before reopening', + tag: 'USB Serial', + ); + try { + await pendingDisconnect; + } catch (_) { + // Failures are already logged by the teardown path. + } + } + _status = UsbSerialStatus.connecting; var normalizedPortName = normalizeUsbPortName(portName); _frameDecoder.reset(); @@ -163,24 +183,7 @@ class UsbSerialService { // // This must happen before we register any new NativeCallable, so it must // be the very first thing we do in the desktop branch. - // A previous disconnect may still be running: its native close waits out - // the kernel's closing_wait in a helper isolate, and it only marks the - // transport disconnected afterwards. fl_close() and fl_free() mutate the - // same process-global flserial_tab, so reopening now could race the - // helper, and the old teardown could later overwrite the new connection - // state. Wait for the whole teardown, not just the native close. - final pendingDisconnect = _activeDisconnect; - if (pendingDisconnect != null) { - _debugLogService?.info( - 'Waiting for the previous USB disconnect to finish before reopening', - tag: 'USB Serial', - ); - try { - await pendingDisconnect; - } catch (_) { - // Failures are already logged by the teardown path. - } - } + // (the previous teardown was already awaited above) try { bindings.fl_free(); From fa9e9d18cd08c818d118b39097a435de0f50d323 Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Sun, 13 Sep 2026 15:42:34 +0200 Subject: [PATCH 06/10] Suppress connector state publication after dispose Fifth review round: - MeshCoreConnector.dispose() sets _disposed, and _setState(), notifyListeners() and markNotifyDirty() no-op afterwards. A teardown started before disposal can still be running (the USB native close waits out the kernel's closing_wait off the UI isolate), and its tail would otherwise call notifyListeners() on a disposed ChangeNotifier. - _handleSerialData() now only drops callbacks in the teardown states (disconnecting/disconnected) instead of everything that is not `connected`, so data arriving in the `connecting` window is still ingested and buffered by the frame decoder. --- lib/connector/meshcore_connector.dart | 8 ++++++++ lib/services/usb_serial_service_native.dart | 6 ++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 25046783..714ed0b8 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -194,6 +194,10 @@ class MeshCoreConnector extends ChangeNotifier { /// waits out the kernel's closing_wait off the UI isolate, so the teardown /// can outlive the tap that starts the next connection. Future? _activeDisconnect; + /// Set by [dispose]. A teardown started before disposal can still be running + /// (the USB native close waits out the kernel's closing_wait off the UI + /// isolate), so state publication is suppressed once the connector is gone. + bool _disposed = false; final MeshCoreUsbManager _usbManager = MeshCoreUsbManager(); final LinuxBlePairingService _linuxBlePairingService = LinuxBlePairingService(); @@ -6944,6 +6948,7 @@ class MeshCoreConnector extends ChangeNotifier { } void _setState(MeshCoreConnectionState newState) { + if (_disposed) return; if (_state != newState) { _state = newState; notifyListeners(); @@ -6951,6 +6956,7 @@ class MeshCoreConnector extends ChangeNotifier { } void markNotifyDirty() { + if (_disposed) return; if (_notifyListenersDirty && _notifyListenersTimer != null) { return; } @@ -6981,11 +6987,13 @@ class MeshCoreConnector extends ChangeNotifier { @override void notifyListeners() { + if (_disposed) return; markNotifyDirty(); } @override void dispose() { + _disposed = true; _scanSubscription?.cancel(); _isScanningSubscription?.cancel(); _connectionSubscription?.cancel(); diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index 781dfcb9..2d5f3d64 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -527,10 +527,12 @@ class UsbSerialService { } void _handleSerialData(FlSerialEventArgs event) { - if (_status != UsbSerialStatus.connected) { + if (_status == UsbSerialStatus.disconnecting || + _status == UsbSerialStatus.disconnected) { // Teardown already invalidated the native handle; a callback queued // before that would make readList() throw and publish a spurious - // transport error that triggers another disconnect. + // transport error that triggers another disconnect. Data that arrives + // while still `connecting` is kept — the decoder buffers it. return; } try { From 1b5ebf6834f63882eee80e35f1b0e9eb3fcf869d Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Sun, 13 Sep 2026 17:22:34 +0200 Subject: [PATCH 07/10] Honor manual disconnect and re-validate state after waiting Sixth review round: - disconnect(manual: true) joining an in-flight automatic teardown now still marks it manual (and cancels the reconnect timer / stops the background service), so a user-initiated disconnect can no longer be followed by an auto-reconnect scheduled by the teardown it joined. - _shouldAutoReconnect is false once _disposed, so a teardown that outlives disposal cannot arm a timer that calls connect() on a disposed connector. - connect()/connectUsb()/connectTcp() and UsbSerialService.connect() re-check the connection state after awaiting the in-flight teardown. The await is a suspension point, so two callers could previously pass the initial guard, resume together and both run the open sequence. --- analysis_options.yaml | 9 +++++ lib/connector/meshcore_connector.dart | 39 ++++++++++++++++++++- lib/services/usb_serial_service_native.dart | 7 ++++ 3 files changed, 54 insertions(+), 1 deletion(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index 0d290213..bf8d4218 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -7,6 +7,15 @@ # The following line activates a set of recommended lints for Flutter apps, # packages, and plugins designed to encourage good coding practices. +analyzer: + exclude: + - build/** + - android/** + - ios/** + - web/** + - windows/** + - macos/** + - linux/** include: package:flutter_lints/flutter.yaml linter: diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 714ed0b8..7672fff1 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -1774,6 +1774,16 @@ class MeshCoreConnector extends ChangeNotifier { ); await _awaitActiveDisconnect(); + // The await is a suspension point: another connect may have claimed the + // connector while this one was waiting for the teardown. + if (_state == MeshCoreConnectionState.connecting || + _state == MeshCoreConnectionState.connected) { + _appDebugLogService?.warn( + 'connectUsb ignored: already $_state after disconnect wait', + tag: 'USB', + ); + return; + } await stopScan(); _cancelReconnectTimer(); @@ -1873,6 +1883,16 @@ class MeshCoreConnector extends ChangeNotifier { _appDebugLogService?.info('connectTcp: endpoint=$host:$port', tag: 'TCP'); await _awaitActiveDisconnect(); + // The await is a suspension point: another connect may have claimed the + // connector while this one was waiting for the teardown. + if (_state == MeshCoreConnectionState.connecting || + _state == MeshCoreConnectionState.connected) { + _appDebugLogService?.warn( + 'connectTcp ignored: already $_state after disconnect wait', + tag: 'TCP', + ); + return; + } await stopScan(); _cancelReconnectTimer(); @@ -2023,6 +2043,12 @@ class MeshCoreConnector extends ChangeNotifier { } await _awaitActiveDisconnect(); + // The await is a suspension point: another connect may have claimed the + // connector while this one was waiting for the teardown. + if (_state == MeshCoreConnectionState.connecting || + _state == MeshCoreConnectionState.connected) { + return; + } _activeTransport = MeshCoreTransportType.bluetooth; @@ -2710,6 +2736,7 @@ class MeshCoreConnector extends ChangeNotifier { } bool get _shouldAutoReconnect => + !_disposed && !_manualDisconnect && _lastDeviceId != null && _activeTransport == MeshCoreTransportType.bluetooth; @@ -2765,7 +2792,17 @@ class MeshCoreConnector extends ChangeNotifier { bool skipBleDeviceDisconnect = false, }) { final inFlight = _activeDisconnect; - if (inFlight != null) return inFlight; + if (inFlight != null) { + if (manual) { + // A teardown started as automatic must still honour a later manual + // request, otherwise _manualDisconnect stays false and its tail + // schedules an auto-reconnect the user did not ask for. + _manualDisconnect = true; + _cancelReconnectTimer(); + unawaited(_backgroundService?.stop()); + } + return inFlight; + } final teardown = _disconnectInternal( manual: manual, skipBleDeviceDisconnect: skipBleDeviceDisconnect, diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index 2d5f3d64..f78210c7 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -144,6 +144,13 @@ class UsbSerialService { } catch (_) { // Failures are already logged by the teardown path. } + + // The await above is a suspension point: another caller may have claimed + // the transport while this one waited. + if (_status == UsbSerialStatus.connected || + _status == UsbSerialStatus.connecting) { + throw StateError('USB serial transport is already active'); + } } _status = UsbSerialStatus.connecting; From 2910dc9f6783535a537379859a5831cc28f143f7 Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Thu, 17 Sep 2026 23:12:52 +0200 Subject: [PATCH 08/10] Apply dart format --- lib/connector/meshcore_connector.dart | 2 ++ lib/services/usb_serial_service_native.dart | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 7672fff1..d3d16f4d 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -188,12 +188,14 @@ class MeshCoreConnector extends ChangeNotifier { String? _lastDeviceId; String? _lastDeviceDisplayName; bool _manualDisconnect = false; + /// Non-null while [disconnect] is tearing the transport down. Connect paths /// join it so a teardown cannot finish after a new connection and reset the /// state to `disconnected`. USB made this reachable: its native close now /// waits out the kernel's closing_wait off the UI isolate, so the teardown /// can outlive the tap that starts the next connection. Future? _activeDisconnect; + /// Set by [dispose]. A teardown started before disposal can still be running /// (the USB native close waits out the kernel's closing_wait off the UI /// isolate), so state publication is suppressed once the connector is gone. diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index f78210c7..cc76ddea 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -35,6 +35,7 @@ class UsbSerialService { String? _connectedPortKey; String? _connectedPortLabel; FlSerial? _serial; + /// Non-null while a disconnect teardown (native close in a helper isolate, /// then subscription cancel) is running. Future? _activeDisconnect; @@ -341,7 +342,6 @@ class UsbSerialService { } Future _disconnectInternal() async { - final portLabel = _connectedPortLabel ?? _connectedPortKey; _debugLogService?.info( 'USB disconnect starting port=${portLabel ?? 'unknown'}', From 9ac1bff7e1750c0901f7d4bf1932be9f1b68f426 Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Thu, 17 Sep 2026 23:09:55 +0200 Subject: [PATCH 09/10] Make pyx URL parsing tests hermetic flutter_test blocks real HTTP, so the two pyx tests could never pass in CI. Inject an overridable http.Client and drive them with MockClient. (cherry picked from commit fb032ef0ee8c53c3683e18cdb9d606c8dfddb47a) --- lib/helpers/message_url_image_helper.dart | 15 ++++++++++----- .../message_url_image_helper_test.dart | 19 +++++++++++++++++-- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/lib/helpers/message_url_image_helper.dart b/lib/helpers/message_url_image_helper.dart index d917af6d..0951dfda 100644 --- a/lib/helpers/message_url_image_helper.dart +++ b/lib/helpers/message_url_image_helper.dart @@ -16,6 +16,12 @@ class MessageUrlImageHelper { static final LinkedHashMap> _messageImageCache = LinkedHashMap>(); + /// HTTP client used to resolve sharing pages. + /// + /// Tests override this because `flutter_test` blocks real network requests. + @visibleForTesting + static http.Client? httpClient; + static final RegExp _pyxPattern = RegExp( r'''https?://pyx\.li/\?i=([^\s<>'"`]+)''', caseSensitive: false, @@ -132,8 +138,9 @@ class MessageUrlImageHelper { static Future _extractFromUrl(String pageUrl, RegExp pattern) async { try { - final response = await http - .get(Uri.parse(pageUrl)) + final uri = Uri.parse(pageUrl); + final client = httpClient; + final response = await (client == null ? http.get(uri) : client.get(uri)) .timeout(const Duration(seconds: 8)); if (response.statusCode < 200 || response.statusCode >= 300) { return null; @@ -141,9 +148,7 @@ class MessageUrlImageHelper { final value = pattern.firstMatch(response.body)?.group(1); if (value == null || value.isEmpty) return null; - final imageUrl = Uri.parse( - pageUrl, - ).resolve(value.replaceAll('&', '&')); + final imageUrl = uri.resolve(value.replaceAll('&', '&')); return imageUrl.scheme == 'http' || imageUrl.scheme == 'https' ? imageUrl.toString() : null; diff --git a/test/helpers/message_url_image_helper_test.dart b/test/helpers/message_url_image_helper_test.dart index ecb2712b..11e1b022 100644 --- a/test/helpers/message_url_image_helper_test.dart +++ b/test/helpers/message_url_image_helper_test.dart @@ -1,23 +1,38 @@ import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; import 'package:meshcore_open/helpers/message_url_image_helper.dart'; void main() { group('MessageUrlImageHelper', () { + tearDown(() => MessageUrlImageHelper.httpClient = null); + + void mockPyxPage(String id) { + MessageUrlImageHelper.httpClient = MockClient((request) async { + expect(request.url.toString(), 'https://pyx.li/?i=$id'); + return http.Response( + '', + 200, + headers: {'content-type': 'text/html; charset=utf-8'}, + ); + }); + } + test('parses short pyx ids', () async { + mockPyxPage('RzmdkTsE'); final attachment = await MessageUrlImageHelper.parse( 'my picture: https://pyx.li/?i=RzmdkTsE text', ); - expect(attachment, isNotNull); expect(attachment, 'https://pyx.li/i/RzmdkTsE.jpg'); }); test('parses direct pyx image urls', () async { + mockPyxPage('Cd1KFiwu'); final attachment = await MessageUrlImageHelper.parse( 'https://pyx.li/?i=Cd1KFiwu', ); - expect(attachment, isNotNull); expect(attachment, 'https://pyx.li/i/Cd1KFiwu.jpg'); }); From d74c280ea3581c33be3cfce1c5510d744082983f Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 27 Sep 2026 11:50:55 -0700 Subject: [PATCH 10/10] Fix USB buffer leak on dispose and guard fl_free against orphaned close dispose() no longer relies on FlSerial.closePort() to free the I/O buffers: it checks the buffers' first byte instead of their address, so it usually leaked both. Close via fl_close and always free by address. A native close still running in a helper isolate is invisible to a fresh isolate after hot restart, so connect() could fl_free() a slot mid-close. Track the in-flight close with a per-process temp marker and wait for it (bounded to 45s) before resetting the slot table. --- lib/services/usb_serial_service_native.dart | 80 +++++++++++++++------ 1 file changed, 60 insertions(+), 20 deletions(-) diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index cd99624e..7ef2eec0 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -39,6 +39,14 @@ class UsbSerialService { /// Non-null while a disconnect teardown (native close in a helper isolate, /// then subscription cancel) is running. Future? _activeDisconnect; + + /// Exists while a native close runs in a helper isolate. flserial's slot + /// table is process-global and survives a hot restart, but + /// [_activeDisconnect] does not, so a fresh isolate checks this marker + /// before fl_free() tears down a slot that is still inside close(). + static final String _pendingClosePath = + '${Directory.systemTemp.path}/meshcore_open_usb_close_$pid'; + static const Duration _maxPendingClose = Duration(seconds: 45); AppDebugLogService? _debugLogService; Object? _lastError; @@ -192,6 +200,7 @@ class UsbSerialService { // This must happen before we register any new NativeCallable, so it must // be the very first thing we do in the desktop branch. // (the previous teardown was already awaited above) + await _waitForOrphanedNativeClose(); try { bindings.fl_free(); @@ -428,15 +437,23 @@ class UsbSerialService { Future _closePortOffUiIsolate(FlSerial serial) async { final flh = serial.flh; if (flh < 0) { - // Already closed synchronously by dispose(); `closePort()` freed the - // native slot, the stream and both I/O buffers. Touching them again - // would double-free the calloc'd buffers. + // Already closed synchronously by dispose(), which also closed the + // stream and freed both I/O buffers. return; } serial.flh = -1; final startedAt = DateTime.now(); + final markerPath = _pendingClosePath; try { - await Isolate.run(() => bindings.fl_close(flh)); + File(markerPath).writeAsStringSync(''); + } catch (_) {} + try { + await Isolate.run(() { + bindings.fl_close(flh); + try { + File(markerPath).deleteSync(); + } catch (_) {} + }); } catch (error) { // Spawning the helper failed, so the native slot and its SerialThread // are still alive with no reachable handle. Close it inline instead — @@ -451,6 +468,9 @@ class UsbSerialService { // Ignore errors while closing. } } + try { + File(markerPath).deleteSync(); + } catch (_) {} final elapsed = DateTime.now().difference(startedAt); if (elapsed > const Duration(seconds: 1)) { _debugLogService?.warn( @@ -467,19 +487,37 @@ class UsbSerialService { _releaseSerialBuffers(serial); } - /// Frees the two calloc'd I/O buffers `openPort()` allocated and clears the - /// pointer fields. - /// - /// [alreadyFreed] is set when `FlSerial.closePort()` ran: it frees both - /// buffers itself but leaves the pointer fields dangling, so they must only - /// be cleared, never freed again. - void _releaseSerialBuffers(FlSerial serial, {bool alreadyFreed = false}) { + /// Waits for a native close left running by a previous isolate (hot + /// restart during a slow close). Bounded by the marker's age so a stale + /// marker — its helper isolate killed before deleting it — cannot block + /// forever. + Future _waitForOrphanedNativeClose() async { + final marker = File(_pendingClosePath); try { - if (!alreadyFreed && serial.serialReadBuff.address != 0) { + if (!marker.existsSync()) return; + _debugLogService?.info( + 'Waiting for a USB port close left over from a previous isolate', + tag: 'USB Serial', + ); + final deadline = marker.lastModifiedSync().add(_maxPendingClose); + while (marker.existsSync() && DateTime.now().isBefore(deadline)) { + await Future.delayed(const Duration(milliseconds: 250)); + } + if (marker.existsSync()) marker.deleteSync(); + } catch (_) {} + } + + /// Frees the two calloc'd I/O buffers `openPort()` allocated and clears the + /// pointer fields. `FlSerial.closePort()` is never used for this: it tests + /// the buffers' first byte (`.value`) instead of their address, so it + /// usually leaks them. + void _releaseSerialBuffers(FlSerial serial) { + try { + if (serial.serialReadBuff.address != 0) { calloc.free(serial.serialReadBuff); } serial.serialReadBuff = Pointer.fromAddress(0); - if (!alreadyFreed && serial.serialWriteBuff.address != 0) { + if (serial.serialWriteBuff.address != 0) { calloc.free(serial.serialWriteBuff); } serial.serialWriteBuff = Pointer.fromAddress(0); @@ -510,22 +548,24 @@ class UsbSerialService { // Close on any live handle, not only when isOpen() reports `open`: // flserial keeps a valid slot (and a running SerialThread) when the // port is in an I/O error state, and _serial is already unreachable. - var closed = false; - if (serial.flh >= 0) { + final flh = serial.flh; + if (flh >= 0) { try { serial.setDTR(false); } catch (_) { // Line-control failure must not skip the close below. } + serial.flh = -1; try { - serial.closePort(); // synchronous C call — kills the SerialThread - closed = true; + bindings.fl_close( + flh, + ); // synchronous C call — kills the SerialThread } catch (_) {} + unawaited(serial.onSerialData.close()); } // _serial is gone, so the disconnect() below can no longer reach the - // buffers: release them here, or just clear the dangling pointers if - // closePort() already freed them. - _releaseSerialBuffers(serial, alreadyFreed: closed); + // buffers: release them here. + _releaseSerialBuffers(serial); } } // Kick off the full async teardown for anything else (subscription cancel,