diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 3bfe1555..342c3045 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -3416,10 +3416,31 @@ class MeshCoreConnector extends ChangeNotifier { return; } messages[index] = update(messages[index]); - _channelMessageStore.saveChannelMessages(channelIndex, messages); + _channelMessageStore.saveChannelMessages(channelIndex, [messages[index]]); notifyListeners(); } + /// Saves only the messages in [messages] that are not in [before]: the ones a + /// mutation added or replaced. Every edit to a channel message replaces it + /// with a `copyWith` copy, so object identity tells changed from unchanged. + /// + /// Saving the whole window instead wrote every message in memory into the + /// channel's stored history, so one wrong view, such as another radio's + /// messages left on this slot, became permanent on the next save (#1163). + Future _saveChannelChanges( + int channelIndex, + List messages, + List before, + ) async { + final unchanged = Set.identity()..addAll(before); + final changed = [ + for (final m in messages) + if (!unchanged.contains(m)) m, + ]; + if (changed.isEmpty) return; + await _channelMessageStore.saveChannelMessages(channelIndex, changed); + } + void _recordPathResult( String contactPubKeyHex, PathSelection selection, @@ -3957,6 +3978,8 @@ class MeshCoreConnector extends ChangeNotifier { _bleInitialSyncStarted = false; if (PlatformInfo.isWeb) { _resetConnectionHandshakeState(); + } else { + _dropPreviousRadioState(); } unawaited(_backgroundService?.start()); notifyListeners(); @@ -4637,21 +4660,33 @@ class MeshCoreConnector extends ChangeNotifier { _selfInfoRetryTimer = null; _hasReceivedDeviceInfo = false; _slotCountKnown = false; - // Drop the previous radio's in-memory history before a new connection loads - // its own. These caches are keyed by channel index / contact key, not by - // radio, so without this a radio switch would keep showing the prior - // radio's channel and DM history (a new radio's empty store cannot - // overwrite them). On-disk stores are already per-radio (device+PSK); this - // is purely the runtime cache. Repopulated on connect by - // loadAllChannelMessages and _loadMessagesForContact. (#472) - _channelMessages.clear(); - _conversations.clear(); - _loadedConversationKeys.clear(); + _dropPreviousRadioState(); _resetSyncProgressState(); _bleInitialSyncStarted = false; _pathHashByteWidth = 1; } + /// Drops everything in memory that belongs to the last radio, before a new + /// connection loads its own. Every connect calls this, on every transport. + /// + /// These caches are keyed by slot index or contact key, never by radio. Kept + /// across a switch, the previous radio's slot-N messages sat in the next + /// radio's slot-N window, and its next message on that slot saved the whole + /// window into its own channel there (#1163; #472 put the clear only in + /// [_resetConnectionHandshakeState], which the Bluetooth connect ran on the + /// web alone). The channel lists go too: they answer which channel a slot + /// holds, and the previous radio's answer is wrong for this one. All of it + /// reloads from this radio's own store at SELF_INFO. + void _dropPreviousRadioState() { + _channelMessages.clear(); + _conversations.clear(); + _loadedConversationKeys.clear(); + _channels.clear(); + _previousChannelsCache.clear(); + _cachedChannels = []; + _recalculateCachedChannelsUnreadTotal(); + } + @visibleForTesting void resetConnectionHandshakeStateForTest() => _resetConnectionHandshakeState(); @@ -6410,8 +6445,9 @@ class MeshCoreConnector extends ChangeNotifier { // Process reaction locally to update the UI immediately. This is our own // outgoing reaction, so the reactor is us. + final before = List.of(messages); _processReaction(messages, reactionInfo, _selfName ?? 'Me'); - await _channelMessageStore.saveChannelMessages(channel.index, messages); + await _saveChannelChanges(channel.index, messages, before); // Mark this reaction as processed _processedChannelReactions[channel.index]!.add(reactionIdentifier); @@ -10978,7 +11014,9 @@ class MeshCoreConnector extends ChangeNotifier { ); _pendingChannelSentQueue.remove(messageId); unawaited( - _channelMessageStore.saveChannelMessages(entry.key, channelMessages), + _channelMessageStore.saveChannelMessages(entry.key, [ + channelMessages[i], + ]), ); notifyListeners(); return true; @@ -11003,7 +11041,9 @@ class MeshCoreConnector extends ChangeNotifier { status: ChannelMessageStatus.failed, ); unawaited( - _channelMessageStore.saveChannelMessages(channelIndex, channelMessages), + _channelMessageStore.saveChannelMessages(channelIndex, [ + channelMessages[i], + ]), ); notifyListeners(); return; @@ -11675,6 +11715,7 @@ class MeshCoreConnector extends ChangeNotifier { if (!isDuplicate) { // New reaction - process it. The reactor is the frame's sender. + final before = List.of(messages); final matched = _processReaction( messages, reactionInfo, @@ -11689,8 +11730,7 @@ class MeshCoreConnector extends ChangeNotifier { DateTime.now(), ); } - // Save updated messages - _channelMessageStore.saveChannelMessages(channelIndex, messages); + unawaited(_saveChannelChanges(channelIndex, messages, before)); // Mark as processed _processedChannelReactions[channelIndex]!.add(reactionIdentifier); @@ -11702,6 +11742,7 @@ class MeshCoreConnector extends ChangeNotifier { // auto reply-block (it guessed the target by most-recent sender, which // mis-attributed and ate screen space). See #37. final ChannelMessage processedMessage = message; + final before = List.of(messages); final existingIndex = _findChannelRepeatIndex(messages, processedMessage); var isNew = true; @@ -11751,8 +11792,7 @@ class MeshCoreConnector extends ChangeNotifier { DateTime.now(), ); - // Save to persistent storage - _channelMessageStore.saveChannelMessages(channelIndex, messages); + unawaited(_saveChannelChanges(channelIndex, messages, before)); return isNew; } diff --git a/test/connector/radio_switch_misfile_test.dart b/test/connector/radio_switch_misfile_test.dart new file mode 100644 index 00000000..d555ddf8 --- /dev/null +++ b/test/connector/radio_switch_misfile_test.dart @@ -0,0 +1,225 @@ +// #1163: switching radios over Bluetooth copied the previous radio's channel +// messages into the next radio's history. +// +// #472 put the in-memory clear in _resetConnectionHandshakeState, but the +// native Bluetooth connect only ran that on the web. Radio A's messages stayed +// in memory under their slot numbers; the next message on the same slot from +// radio B saved the whole list into B's channel for that slot. The owner's +// Windows store held 2,893 such copies, each with the same receive time under +// two radios. +// +// These tests go through the real connect, not the reset, because the old #472 +// test called the reset directly and passed while Bluetooth never ran it. + +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_blue_plus/flutter_blue_plus.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List _channelInfoFrame(Channel ch) { + final frame = Uint8List(50); + frame[0] = respCodeChannelInfo; + frame[1] = ch.index; + final nameBytes = ch.name.codeUnits; + for (var i = 0; i < nameBytes.length && i < 31; i++) { + frame[2 + i] = nameBytes[i]; + } + frame.setRange(34, 50, ch.psk); + return frame; +} + +Uint8List _channelMsgFrame({required int channelIdx, required String text}) { + return Uint8List.fromList([ + respCodeChannelMsgRecvV3, + 0, + 0, + 0, + channelIdx, + 1, + txtTypePlain, + 0x40, + 0xE2, + 0x01, + 0x00, + ...text.codeUnits, + ]); +} + +Channel _channel(int index, String name, int pskSeed) => Channel( + index: index, + name: name, + psk: Uint8List.fromList(List.generate(16, (i) => (pskSeed + i) & 0xFF)), +); + +Future _settle([int turns = 25]) async { + for (var i = 0; i < turns; i++) { + await Future.delayed(Duration.zero); + } +} + +final _radioA = Uint8List.fromList(List.generate(32, (i) => i)); +final _radioB = Uint8List.fromList(List.generate(32, (i) => 99 + i)); + +String _hex(Uint8List key) => + key.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late OffbandDatabase db; + late MeshCoreConnector c; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + c = MeshCoreConnector(); + c.initialize( + retryService: MessageRetryService(), + pathHistoryService: PathHistoryService(StorageService()), + ); + c.sendFrameOverrideForTest = (_) {}; + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + // [savedList] is what the connect-time startup load reads back for a radio + // this app has used before: its own last confirmed channel list. + Future becomeRadio( + Uint8List key, + List layout, { + List? savedList, + }) async { + c.setConnectedForTest(); + c.setSelfPublicKeyForTest(key); + c.wireMessageStoreForTest(); + if (savedList != null) c.seedCachedChannelsForTest(savedList); + await c.getChannels(force: true, maxChannels: layout.length); + for (final ch in layout) { + c.handleFrameForTest(_channelInfoFrame(ch)); + await _settle(2); + } + await _settle(); + } + + // The radio switch the owner does: drop radio A, connect radio B over + // Bluetooth. The fake device cannot actually connect in a test; what matters + // is everything the connect does before it reaches the radio. + Future switchOverBluetooth() async { + await c.disconnect(manual: true); + try { + await c + .connect(BluetoothDevice.fromId('00:11:22:33:44:55')) + .timeout(const Duration(seconds: 5)); + } catch (_) {} + } + + Future> storedTexts(Uint8List radio, Channel ch) async { + final store = ChannelMessageStore() + ..setPublicKeyHex = _hex(radio) + ..channelPskResolver = ((_) => ch.pskHex); + return (await store.loadChannelMessages( + ch.index, + )).map((m) => m.text).toList(); + } + + test("a Bluetooth connect drops the previous radio's channel and DM history " + 'from memory', () async { + final alpha = _channel(0, 'Alpha', 10); + await becomeRadio(_radioA, [alpha]); + c.handleFrameForTest(_channelMsgFrame(channelIdx: 0, text: 'A: one')); + await _settle(); + c.conversationsForTest['deadbeef00'] = []; + c.loadedConversationKeysForTest.add('deadbeef00'); + expect(c.channelMessagesForTest[0], isNotEmpty); + + await switchOverBluetooth(); + + expect(c.channelMessagesForTest, isEmpty); + expect(c.conversationsForTest, isEmpty); + expect(c.loadedConversationKeysForTest, isEmpty); + expect( + c.channels, + isEmpty, + reason: "radio A's channel list must not answer for radio B's slots", + ); + expect(c.cachedChannels, isEmpty); + }); + + test("returning to radio B never saves radio A's messages into B's channel on " + 'the same slot', () async { + final alpha = _channel(0, 'Alpha', 10); + final gamma = _channel(0, 'Gamma', 70); + + await becomeRadio(_radioA, [alpha]); + c.handleFrameForTest(_channelMsgFrame(channelIdx: 0, text: 'A: from A')); + await _settle(); + + // Radio B has been used before, so its saved list already says slot 0 is + // Gamma. The post-sync check then sees no change on slot 0 and keeps + // whatever is in memory there, which before the fix was radio A's history. + await switchOverBluetooth(); + await becomeRadio(_radioB, [gamma], savedList: [gamma]); + c.handleFrameForTest(_channelMsgFrame(channelIdx: 0, text: 'B: from B')); + await _settle(); + + expect( + await storedTexts(_radioB, gamma), + ['from B'], + reason: + "the bug: radio A's slot-0 message was saved into radio B's " + 'slot-0 channel', + ); + expect(await storedTexts(_radioA, alpha), ['from A']); + expect( + (c.channelMessagesForTest[0] ?? const []).map( + (m) => m.text, + ), + ['from B'], + ); + }); + + test( + 'a new message saves only itself, never the rest of the window', + () async { + // Defense in depth: whatever else is in memory for a slot, right or wrong, + // a new arrival must not write it into the channel's stored history. + final gamma = _channel(0, 'Gamma', 70); + await becomeRadio(_radioB, [gamma]); + c.channelMessagesForTest[0] = [ + ChannelMessage( + senderName: 'Elsewhere', + text: 'stray, never stored here', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000), + isOutgoing: false, + status: ChannelMessageStatus.sent, + channelIndex: 0, + ), + ]; + + c.handleFrameForTest(_channelMsgFrame(channelIdx: 0, text: 'B: new')); + await _settle(); + + expect(await storedTexts(_radioB, gamma), ['new']); + }, + ); +}