diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index f535ed25..a706e715 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -5902,13 +5902,20 @@ class MeshCoreConnector extends ChangeNotifier { await sendFrame(buildSetChannelFrame(index, '', Uint8List(16))); _channelMessages.remove(index); _processedChannelReactions.remove(index); - // Refresh before clearing history so messages from an in-flight queue sync - // cannot recreate the channel's stored history after it has been deleted. - await getChannels(force: true); - // Another slot holding the same PSK keeps the shared history. - final stillHeld = _slotChannelIds.containsValue(channelId); - if (channelId != null && !stillHeld) { - await _clearChannelStorage(channelId); + try { + // Refresh before clearing history so messages from an in-flight queue + // sync cannot recreate the channel's stored history after it is deleted. + await getChannels(force: true); + } finally { + // Another slot holding the same PSK keeps the shared history. The + // deleted slot is skipped: a failed or partial refresh can leave it in + // the map. + final stillHeld = _slotChannelIds.entries.any( + (entry) => entry.key != index && entry.value == channelId, + ); + if (channelId != null && !stillHeld) { + await _clearChannelStorage(channelId); + } } } diff --git a/test/connector/channel_slot_map_test.dart b/test/connector/channel_slot_map_test.dart index 65097f67..d2f217ce 100644 --- a/test/connector/channel_slot_map_test.dart +++ b/test/connector/channel_slot_map_test.dart @@ -243,6 +243,40 @@ void main() { expect(_storedTexts(hikingId), isEmpty); }); + test('deleting a channel clears its history when the refresh cannot read ' + 'the slot', () async { + _connector.channelSyncTimeoutMs = 30; + var deleted = false; + final radio = _TestRadio( + swallow: (frame) { + if (frame[0] == cmdSetChannel && frame[1] == 1) deleted = true; + return deleted && frame[0] == cmdGetChannel && frame[1] == 1; + }, + ); + await _connect(radio); + await _waitFor(() => _texts(1).contains(_queuedHikingText)); + + await _connector.deleteChannel(1); + expect(_connector.channelIdForSlot(1), hikingId); + expect(_storedTexts(hikingId), isEmpty); + }); + + test( + 'deleting one of two slots with the same PSK keeps the history', + () async { + final radio = _TestRadio(); + await _connect( + radio, + seed: () => + radio.handle(buildSetChannelFrame(5, 'Hiking Twin', _psk(1))), + ); + await _waitFor(() => _texts(1).contains(_queuedHikingText)); + + await _connector.deleteChannel(1); + expect(_storedTexts(hikingId), contains(_queuedHikingText)); + }, + ); + test('a channel frame that arrives before the slot map is held, then filed ' 'by the confirmed map', () async { final radio = _TestRadio(