From b6302d70651f426ebc74c2ddd485fda85b725063 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:15:34 -0500 Subject: [PATCH 1/7] fix(#1163): a Bluetooth connect drops the previous radio's history Native Bluetooth connects never ran _resetConnectionHandshakeState (web only), so the #472 clear never happened there. The last radio's messages stayed in memory under their slot numbers, and the next message on that slot from the new radio saved the whole window into the new radio's channel. The owner's Windows store held 2,893 such copies. Every connect now drops the previous radio's message windows, DM conversations and channel lists, on every transport. Saves write only the messages a change added or replaced, never the whole window, so a wrong view can no longer become stored history. Co-Authored-By: Claude Opus 5.5 --- lib/connector/meshcore_connector.dart | 76 ++++-- test/connector/radio_switch_misfile_test.dart | 225 ++++++++++++++++++ 2 files changed, 283 insertions(+), 18 deletions(-) create mode 100644 test/connector/radio_switch_misfile_test.dart 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']); + }, + ); +} From 53ecfbe75c7458825e00c55327eae5424e7542a8 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:24:55 -0500 Subject: [PATCH 2/7] fix(#1163): hold aside channel messages copied between radios A Bluetooth radio switch saved the previous radio's messages into the next radio's channels. Each copy kept the original's receive time exactly, which two separate receptions never share, so the copies can be found. The original is on the radio that was connected when the message arrived, judged from each radio's own receptions. Where exactly one radio was connected, the others' rows are moved to a held_1163_copy key nothing reads; they are not deleted and can be moved back. Where no radio or several were connected, nothing is touched. Runs once at startup, logs its counts, and retries on the next launch if it fails. On a copy of the owner's Windows store: 2,864 rows held aside, 294 messages left alone, every held row's original kept, and no held agent alert taken from the channel those alerts belong to. Co-Authored-By: Claude Opus 5.5 --- lib/main.dart | 6 + lib/storage/cross_radio_copy_cleanup.dart | 185 ++++++++++++++++++ lib/storage/drift/blob_store.dart | 51 +++++ .../cross_radio_copy_cleanup_test.dart | 163 +++++++++++++++ 4 files changed, 405 insertions(+) create mode 100644 lib/storage/cross_radio_copy_cleanup.dart create mode 100644 test/storage/cross_radio_copy_cleanup_test.dart diff --git a/lib/main.dart b/lib/main.dart index 5a042e93..e2864c3c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -36,6 +36,7 @@ import 'services/store_consolidation_service.dart'; import 'services/stale_history_sweep.dart'; import 'services/storage_health_service.dart'; import 'services/radio_preset_service.dart'; +import 'storage/cross_radio_copy_cleanup.dart'; import 'storage/drift/blob_store.dart'; import 'widgets/contact_sync_shortfall_banner.dart'; import 'widgets/factory_reset_banner.dart'; @@ -83,6 +84,11 @@ void main() async { // Start always-on file logging (#97); no-op on web. await FileLogService.instance.init(); + // Hold aside channel messages a Bluetooth radio switch copied into another + // radio's history (#1163). One-time, before any store is read into memory, + // and after file logging so its counts reach the log. + await CrossRadioCopyCleanup.run(); + // Restore the desktop window's saved position/size (#349); no-op off desktop. await WindowGeometryService.instance.initialize(); diff --git a/lib/storage/cross_radio_copy_cleanup.dart b/lib/storage/cross_radio_copy_cleanup.dart new file mode 100644 index 00000000..99f88549 --- /dev/null +++ b/lib/storage/cross_radio_copy_cleanup.dart @@ -0,0 +1,185 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; + +import '../utils/app_logger.dart'; +import 'drift/blob_store.dart'; + +/// One stored channel message, as the cleanup sees it. +typedef ScannedRow = ({String storeKey, String mergeKey, int? rxTime}); + +/// What [findCrossRadioCopies] decided. +class CopyDecision { + const CopyDecision({required this.copies, required this.undecided}); + + /// Rows to hold aside: each is a copy whose original is on another radio. + final List copies; + + /// Copied messages left alone because no single radio can be shown to have + /// received them. + final int undecided; +} + +const _channelPrefix = 'channel_messages_'; + +String _radioOf(String storeKey) => + storeKey.substring(_channelPrefix.length, _channelPrefix.length + 10); + +/// Finds channel messages that one radio received and a radio switch then +/// wrote into another radio's history (#1163). +/// +/// A copy keeps the original's receive time (`rxTime`) exactly. Two radios +/// that each heard a packet deliver it at different moments, so the same +/// message under two radios with the same receive time is one reception stored +/// twice. +/// +/// The original is on the radio that was connected when the message arrived. +/// A radio's connected periods come from its own receptions: rows whose +/// receive time no other radio shares. Runs of them with no gap longer than +/// [gap] form a session, and a session covers [gap] either side. When exactly +/// one of the radios holding a copy covers the receive time, the others hold +/// copies. When none or several do, nothing is touched: the stored data cannot +/// say which is real. +/// +/// Run on a copy of the owner's Windows store (2,893 copied messages): 2,864 +/// rows held aside, 294 messages left alone. Every held row's original was +/// kept, and none of the 257 held agent alerts, whose channel is known from +/// their text, came from that channel. +CopyDecision findCrossRadioCopies( + List rows, { + Duration gap = const Duration(minutes: 60), +}) { + final byMessage = >{}; + for (final r in rows) { + if (r.rxTime == null || r.storeKey.length < _channelPrefix.length + 10) { + continue; + } + byMessage.putIfAbsent(r.mergeKey, () => []).add(r); + } + + final ownReceptions = >{}; + final copyGroups = >[]; + for (final group in byMessage.values) { + final byTime = >{}; + for (final r in group) { + byTime.putIfAbsent(r.rxTime!, () => []).add(r); + } + for (final entry in byTime.entries) { + final radios = {for (final r in entry.value) _radioOf(r.storeKey)}; + if (radios.length > 1) { + copyGroups.add(entry.value); + } else { + ownReceptions.putIfAbsent(radios.single, () => []).add(entry.key); + } + } + } + + final gapMs = gap.inMilliseconds; + final sessions = >{}; + ownReceptions.forEach((radio, times) { + times.sort(); + final spans = <(int, int)>[]; + var start = times.first; + var prev = times.first; + for (final t in times.skip(1)) { + if (t - prev > gapMs) { + spans.add((start, prev)); + start = t; + } + prev = t; + } + spans.add((start, prev)); + sessions[radio] = spans; + }); + + bool connectedAt(String radio, int t) { + final spans = sessions[radio]; + if (spans == null) return false; + var lo = 0; + var hi = spans.length - 1; + while (lo <= hi) { + final mid = (lo + hi) >> 1; + final (s, e) = spans[mid]; + if (t < s - gapMs) { + hi = mid - 1; + } else if (t > e + gapMs) { + lo = mid + 1; + } else { + return true; + } + } + return false; + } + + final copies = []; + var undecided = 0; + for (final group in copyGroups) { + final t = group.first.rxTime!; + final radios = {for (final r in group) _radioOf(r.storeKey)}; + final connected = radios.where((radio) => connectedAt(radio, t)).toList(); + if (connected.length != 1) { + undecided++; + continue; + } + copies.addAll(group.where((r) => _radioOf(r.storeKey) != connected.single)); + } + return CopyDecision(copies: copies, undecided: undecided); +} + +CopyDecision _decide(List rows) => findCrossRadioCopies(rows); + +/// Runs [findCrossRadioCopies] once over the stored history and holds the +/// copies aside (#1163). +/// +/// Held, not deleted: each copy moves to [heldPrefix] + its original key, a key +/// nothing reads, so a wrong call can be put back. A marker records the run so +/// it happens once; the counts go to the log either way. +class CrossRadioCopyCleanup { + CrossRadioCopyCleanup._(); + + static const doneMarkerKey = '__cleanup_1163_cross_radio_copies'; + static const heldPrefix = 'held_1163_copy|'; + + static Future run([BlobStore? store]) async { + final blobs = store ?? BlobStore.instance; + try { + if (await blobs.read(doneMarkerKey) != null) return; + final rows = await blobs.messageRowTimes(_channelPrefix); + final decision = await compute(_decide, rows); + + final byKey = >{}; + for (final r in decision.copies) { + byKey.putIfAbsent(r.storeKey, () => []).add(r.mergeKey); + } + for (final entry in byKey.entries) { + await blobs.moveMessageRows( + entry.key, + '$heldPrefix${entry.key}', + entry.value, + ); + } + await blobs.write( + doneMarkerKey, + jsonEncode({ + 'at': DateTime.now().toIso8601String(), + 'held': decision.copies.length, + 'undecided': decision.undecided, + 'keys': {for (final e in byKey.entries) e.key: e.value.length}, + }), + ); + appLogger.info( + 'Cross-radio copy cleanup: scanned ${rows.length} channel messages, ' + 'held aside ${decision.copies.length} copies from ${byKey.length} ' + 'channel histories, left ${decision.undecided} undecided (#1163)', + tag: 'Storage', + ); + } catch (e) { + // No marker is written, so the next launch tries again; the history is + // untouched by a failed move, which runs in one transaction per key. + appLogger.error( + 'Cross-radio copy cleanup failed and will retry next launch: $e', + tag: 'Storage', + ); + } + } +} diff --git a/lib/storage/drift/blob_store.dart b/lib/storage/drift/blob_store.dart index c4d360c2..7a7d5f3a 100644 --- a/lib/storage/drift/blob_store.dart +++ b/lib/storage/drift/blob_store.dart @@ -401,6 +401,57 @@ class BlobStore { } } + /// Every message row whose store key starts with [prefix], as its store key, + /// identity and the app's receive time (`rxTime`, null when absent). + /// + /// The receive time is read with `json_extract` in SQLite, so a scan of the + /// whole history moves three small columns instead of every payload (#1163). + Future> + messageRowTimes(String prefix) async { + final rows = await _db + .customSelect( + "SELECT store_key, merge_key, json_extract(payload, '\$.rxTime') AS rx " + 'FROM message_records WHERE substr(store_key, 1, ?) = ?', + variables: [ + Variable.withInt(prefix.length), + Variable.withString(prefix), + ], + readsFrom: {_db.messageRecords}, + ) + .get(); + return [ + for (final r in rows) + ( + storeKey: r.read('store_key'), + mergeKey: r.read('merge_key'), + rxTime: r.readNullable('rx'), + ), + ]; + } + + /// Moves the rows under [fromKey] whose identity is in [mergeKeys] to + /// [toKey], in one transaction. Nothing is deleted: the rows keep their + /// payloads and can be moved back (#1163). + Future moveMessageRows( + String fromKey, + String toKey, + Iterable mergeKeys, + ) async { + final keys = mergeKeys.toList(); + await _db.transaction(() async { + for (var i = 0; i < keys.length; i += 500) { + final chunk = keys.sublist( + i, + i + 500 > keys.length ? keys.length : i + 500, + ); + await (_db.update(_db.messageRecords)..where( + (t) => t.storeKey.equals(fromKey) & t.mergeKey.isIn(chunk), + )) + .write(MessageRecordsCompanion(storeKey: Value(toKey))); + } + }); + } + /// Removes every message under [storeKey], for the stores' clear paths. Future deleteMessageRows(String storeKey) async { await (_db.delete( diff --git a/test/storage/cross_radio_copy_cleanup_test.dart b/test/storage/cross_radio_copy_cleanup_test.dart new file mode 100644 index 00000000..195fc21d --- /dev/null +++ b/test/storage/cross_radio_copy_cleanup_test.dart @@ -0,0 +1,163 @@ +// #1163: channel messages a Bluetooth radio switch copied into another radio's +// history. A copy keeps the original's receive time exactly; the original is on +// the radio that was connected when the message arrived. + +import 'dart:convert'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/cross_radio_copy_cleanup.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; + +const _a = 'aaaaaaaaaa'; +const _b = 'bbbbbbbbbb'; +String _key(String radio, String psk) => 'channel_messages_${radio}psk_$psk'; + +const _min = 60 * 1000; +const _t0 = 1_800_000_000_000; + +ScannedRow _row(String storeKey, String mergeKey, int rxTime) => + (storeKey: storeKey, mergeKey: mergeKey, rxTime: rxTime); + +// [radio] was connected around [at]: a few receptions only it holds. +List _session(String radio, int at, String tag) => [ + for (var i = 0; i < 3; i++) + _row(_key(radio, 'own'), '$tag-own-$i', at + i * _min), +]; + +void main() { + group('findCrossRadioCopies', () { + test('the field pattern: radio A received it, radio B holds a copy', () { + final rows = [ + ..._session(_a, _t0, 'a'), + ..._session(_b, _t0 + 6 * 60 * _min, 'b'), // B connected 6 hours later + _row(_key(_a, 'claude'), 'alert', _t0 + _min), + _row(_key(_b, 'offband'), 'alert', _t0 + _min), // same slot on B + ]; + + final decision = findCrossRadioCopies(rows); + + expect(decision.copies.map((r) => r.storeKey), [_key(_b, 'offband')]); + expect(decision.undecided, 0); + }); + + test('a message both radios heard, at different times, is no copy', () { + final rows = [ + ..._session(_a, _t0, 'a'), + ..._session(_b, _t0 + 6 * 60 * _min, 'b'), + _row(_key(_a, 'public'), 'heard-twice', _t0 + _min), + _row(_key(_b, 'public'), 'heard-twice', _t0 + 6 * 60 * _min + _min), + ]; + + final decision = findCrossRadioCopies(rows); + + expect(decision.copies, isEmpty); + expect(decision.undecided, 0); + }); + + test( + 'a copy with no connection evidence on either radio is left alone', + () { + final rows = [ + ..._session(_a, _t0, 'a'), + ..._session(_b, _t0 + 6 * 60 * _min, 'b'), + // Three days away from both sessions: nothing says who heard it. + _row(_key(_a, 'echo'), 'orphan', _t0 + 3 * 24 * 60 * _min), + _row(_key(_b, 'test'), 'orphan', _t0 + 3 * 24 * 60 * _min), + ]; + + final decision = findCrossRadioCopies(rows); + + expect(decision.copies, isEmpty); + expect(decision.undecided, 1); + }, + ); + + test('two radios both connected at that time: left alone', () { + final rows = [ + ..._session(_a, _t0, 'a'), + ..._session(_b, _t0, 'b'), + _row(_key(_a, 'echo'), 'either', _t0 + _min), + _row(_key(_b, 'test'), 'either', _t0 + _min), + ]; + + final decision = findCrossRadioCopies(rows); + + expect(decision.copies, isEmpty); + expect(decision.undecided, 1); + }); + }); + + group('CrossRadioCopyCleanup.run', () { + late OffbandDatabase db; + late BlobStore blobs; + + setUp(() { + db = OffbandDatabase(NativeDatabase.memory()); + blobs = BlobStore(db); + }); + + tearDown(() => db.close()); + + Future store(String key, String mergeKey, int rxTime) => + blobs.upsertMessageRows(key, [ + MessageRowInput( + mergeKey: mergeKey, + timestampMs: rxTime, + payload: jsonEncode({'text': mergeKey, 'rxTime': rxTime}), + ), + ]); + + Future seedFieldPattern() async { + for (final r in [ + ..._session(_a, _t0, 'a'), + ..._session(_b, _t0 + 6 * 60 * _min, 'b'), + _row(_key(_a, 'claude'), 'alert', _t0 + _min), + _row(_key(_b, 'offband'), 'alert', _t0 + _min), + ]) { + await store(r.storeKey, r.mergeKey, r.rxTime!); + } + } + + test( + 'holds the copy aside, keeps the original, and can be undone', + () async { + await seedFieldPattern(); + + await CrossRadioCopyCleanup.run(blobs); + + expect(await blobs.messageMergeKeys(_key(_b, 'offband')), isEmpty); + expect(await blobs.messageMergeKeys(_key(_a, 'claude')), {'alert'}); + final held = + '${CrossRadioCopyCleanup.heldPrefix}${_key(_b, 'offband')}'; + expect( + await blobs.messageMergeKeys(held), + {'alert'}, + reason: + 'held, not deleted: the copy is kept where it can be put back', + ); + final marker = jsonDecode( + (await blobs.read(CrossRadioCopyCleanup.doneMarkerKey))!, + ); + expect(marker['held'], 1); + expect(marker['undecided'], 0); + }, + ); + + test( + 'runs once: a later launch does not touch the history again', + () async { + await seedFieldPattern(); + await CrossRadioCopyCleanup.run(blobs); + + // A new copy appearing afterwards is not this cleanup's business. + await store(_key(_b, 'public'), 'later', _t0 + 2 * _min); + await store(_key(_a, 'public'), 'later', _t0 + 2 * _min); + await CrossRadioCopyCleanup.run(blobs); + + expect(await blobs.messageMergeKeys(_key(_b, 'public')), {'later'}); + }, + ); + }); +} From 438b9bc4f92ab964c693919fb6141783ac4150f0 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:33:17 -0500 Subject: [PATCH 3/7] fix(#1163): reload a slot loaded under the wrong channel, and log it The post-sync check compared the radio's channels with the saved list, so a slot whose history had been loaded under some other list kept it. Each slot now records the channel key its in-memory history was loaded under, and a confirmed sync reloads any slot whose channel differs. Every history load and every filed message logs the radio, slot, channel name, PSK fingerprint and which list answered. The Nov logs could not show the misfile because nothing recorded which history a slot held; this does. Co-Authored-By: Claude Opus 5.5 --- lib/connector/meshcore_connector.dart | 65 ++++++++++++++++++- test/connector/radio_switch_misfile_test.dart | 39 +++++++++++ 2 files changed, 102 insertions(+), 2 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 342c3045..da1b0b91 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -369,6 +369,12 @@ class MeshCoreConnector extends ChangeNotifier { final Map> _conversations = {}; final Map> _channelMessages = {}; + /// The channel PSK each slot's in-memory window was loaded under (null: the + /// slot had not resolved, so the slot-index key was read). A confirmed sync + /// reloads any slot whose channel differs from this, which the comparison + /// against the saved list alone cannot see (#1163). + final Map _windowPskHex = {}; + /// Last send timestamp (seconds) used per channel, to keep every channel /// send's `(ts, channel_idx)` key unique for 0xC6 correlation (#524). final Map _lastChannelSendTsSecs = {}; @@ -2931,10 +2937,20 @@ class MeshCoreConnector extends ChangeNotifier { /// Load persisted channel messages for a specific channel Future _loadChannelMessages(int channelIndex) async { + final lookup = _findChannelByIndexWithSource(channelIndex); final allMessages = await _channelMessageStore.loadChannelMessages( channelIndex, ); if (allMessages.isNotEmpty) { + _windowPskHex[channelIndex] = lookup.channel?.pskHex; + _appDebugLogService?.info( + 'History load: radio ' + '${AppSettingsService.radioScopePrefix(selfPublicKeyHex)} slot ' + '$channelIndex "${lookup.channel?.name ?? ''}" psk ' + '${AppSettingsService.pskFingerprint(lookup.channel?.pskHex)} ' + '(${lookup.source}): ${allMessages.length} stored message(s)', + tag: 'Storage', + ); // Keep only the most recent N messages in memory to bound memory usage final windowedMessages = List.from( allMessages.length > _messageWindowSize @@ -4679,6 +4695,7 @@ class MeshCoreConnector extends ChangeNotifier { /// reloads from this radio's own store at SELF_INFO. void _dropPreviousRadioState() { _channelMessages.clear(); + _windowPskHex.clear(); _conversations.clear(); _loadedConversationKeys.clear(); _channels.clear(); @@ -6440,7 +6457,10 @@ class MeshCoreConnector extends ChangeNotifier { } // Get the in-memory messages list (same as _addChannelMessage uses) - _channelMessages.putIfAbsent(channel.index, () => []); + if (!_channelMessages.containsKey(channel.index)) { + _channelMessages[channel.index] = []; + _windowPskHex[channel.index] = channel.pskHex; + } final messages = _channelMessages[channel.index]!; // Process reaction locally to update the UI immediately. This is our own @@ -7219,10 +7239,35 @@ class MeshCoreConnector extends ChangeNotifier { // this slot from the store; the resolver now sees the fresh list, so // the load reads the NEW identity's own history. _channelMessages.remove(fresh.index); + _windowPskHex.remove(fresh.index); unawaited(_loadChannelMessages(fresh.index)); } } + // #1163: the diff above compares the radio with the SAVED list, so it + // cannot see a window that was loaded under some other list. Compare each + // window with the key it was actually loaded under instead, and reload + // any that does not match the channel the radio just confirmed. + for (final fresh in _channels) { + if (!_channelMessages.containsKey(fresh.index) || + !_windowPskHex.containsKey(fresh.index)) { + continue; + } + final loadedAs = _windowPskHex[fresh.index]; + final confirmed = fresh.isEmpty ? null : fresh.pskHex; + if (loadedAs == confirmed) continue; + _appDebugLogService?.warn( + 'Slot ${fresh.index} history was loaded under psk ' + '${AppSettingsService.pskFingerprint(loadedAs)} but the radio holds ' + '"${fresh.name}" psk ${AppSettingsService.pskFingerprint(confirmed)}; ' + 'reloading it from that channel\'s own history', + tag: 'ChannelSync', + ); + _channelMessages.remove(fresh.index); + _windowPskHex.remove(fresh.index); + if (confirmed != null) unawaited(_loadChannelMessages(fresh.index)); + } + if (_erasedChannelSlots.isNotEmpty) { // #1060: the radio answered, but for erased slots. "Device is truth" // assumes the device HAS the truth; erased flash is the device having @@ -7657,6 +7702,7 @@ class MeshCoreConnector extends ChangeNotifier { if (result == ChannelWrite.ok) { await _channelMessageStore.clearChannelMessages(index); _channelMessages.remove(index); + _windowPskHex.remove(index); } if (refresh) _syncAfterChannelWrites(); return result; @@ -7761,6 +7807,7 @@ class MeshCoreConnector extends ChangeNotifier { Future _retireSlotOccupant(int index) async { await _channelMessageStore.clearLegacySlotHistory(index); _channelMessages.remove(index); + _windowPskHex.remove(index); } /// Applies the user's keep-or-delete answer for a key change once the radio @@ -11692,7 +11739,11 @@ class MeshCoreConnector extends ChangeNotifier { } bool _addChannelMessage(int channelIndex, ChannelMessage message) { - _channelMessages.putIfAbsent(channelIndex, () => []); + final lookup = _findChannelByIndexWithSource(channelIndex); + if (!_channelMessages.containsKey(channelIndex)) { + _channelMessages[channelIndex] = []; + _windowPskHex[channelIndex] = lookup.channel?.pskHex; + } final messages = _channelMessages[channelIndex]!; // Parse reaction info. Our own format first, then the PocketMesh / @@ -11781,6 +11832,16 @@ class MeshCoreConnector extends ChangeNotifier { } } else { messages.add(processedMessage); + _appDebugLogService?.info( + 'CHAN FILED slot $channelIndex "${lookup.channel?.name ?? ''}" psk ' + '${AppSettingsService.pskFingerprint(lookup.channel?.pskHex)} ' + '(${lookup.source}), window psk ' + '${AppSettingsService.pskFingerprint(_windowPskHex[channelIndex])}, ' + 'radio ${AppSettingsService.radioScopePrefix(selfPublicKeyHex)}, ' + 'sender=${processedMessage.senderName}', + tag: 'Ingest', + noNotify: true, + ); } // A message just landed, so a reaction that arrived before it may now have diff --git a/test/connector/radio_switch_misfile_test.dart b/test/connector/radio_switch_misfile_test.dart index d555ddf8..db238edb 100644 --- a/test/connector/radio_switch_misfile_test.dart +++ b/test/connector/radio_switch_misfile_test.dart @@ -198,6 +198,45 @@ void main() { ); }); + test('a confirmed sync reloads a slot whose history was loaded under another ' + 'channel, even when the saved list already matches the radio', () async { + final alpha = _channel(0, 'Alpha', 10); + final gamma = _channel(0, 'Gamma', 70); + Future storeHistory(Channel ch, String text) async { + final store = ChannelMessageStore() + ..setPublicKeyHex = _hex(_radioB) + ..channelPskResolver = ((_) => ch.pskHex); + await store.saveChannelMessages(ch.index, [ + ChannelMessage( + senderName: 'X', + text: text, + timestamp: DateTime.fromMillisecondsSinceEpoch(5000), + isOutgoing: false, + status: ChannelMessageStatus.sent, + channelIndex: 0, + ), + ]); + } + + await storeHistory(alpha, 'alpha history'); + await storeHistory(gamma, 'gamma history'); + + c.setConnectedForTest(); + c.setSelfPublicKeyForTest(_radioB); + c.wireMessageStoreForTest(); + // The window loads while slot 0 resolves to Alpha... + c.seedCachedChannelsForTest([alpha]); + await c.loadAllChannelMessages(maxChannels: 1); + expect(c.channelMessagesForTest[0]!.map((m) => m.text), ['alpha history']); + + // ...then the saved list says Gamma, and the radio confirms Gamma. The + // saved-list diff sees no change on slot 0. + await becomeRadio(_radioB, [gamma], savedList: [gamma]); + await _settle(); + + expect(c.channelMessagesForTest[0]!.map((m) => m.text), ['gamma history']); + }); + test( 'a new message saves only itself, never the rest of the window', () async { From 4c86017b11234c5587ab5854e6a5f01421902ce2 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:43:02 -0500 Subject: [PATCH 4/7] feat(#1163): re-read before "not confirmed", and a visible Resync A channel add, rename or delete the radio did not answer was reported as unconfirmed at once, while the re-read that would settle it was still running. The write now waits for that re-read and reports done when the slot holds the change. The error shows only when the re-read disagrees or cannot finish, and it carries a Resync button. A delete confirmed this way clears the deleted channel's history by its own key, since its slot no longer resolves to it. The Channels screen gets a Resync action in the app bar. The only other way to resync was pulling the list down, which nothing said. During a running sync, Resync explains why it is waiting instead of doing nothing. New string channels_resync is English-only; untranslated.json is regenerated. Co-Authored-By: Claude Opus 5.5 --- lib/connector/meshcore_connector.dart | 97 ++++++++++++++++++- lib/helpers/channel_slot_ui.dart | 42 +++++++- lib/l10n/app_en.arb | 8 +- lib/l10n/app_localizations.dart | 10 +- lib/l10n/app_localizations_bg.dart | 5 +- lib/l10n/app_localizations_de.dart | 5 +- lib/l10n/app_localizations_en.dart | 5 +- lib/l10n/app_localizations_es.dart | 5 +- lib/l10n/app_localizations_fr.dart | 5 +- lib/l10n/app_localizations_hu.dart | 5 +- lib/l10n/app_localizations_it.dart | 5 +- lib/l10n/app_localizations_ja.dart | 5 +- lib/l10n/app_localizations_ko.dart | 5 +- lib/l10n/app_localizations_nl.dart | 5 +- lib/l10n/app_localizations_pl.dart | 5 +- lib/l10n/app_localizations_pt.dart | 5 +- lib/l10n/app_localizations_ru.dart | 5 +- lib/l10n/app_localizations_sk.dart | 5 +- lib/l10n/app_localizations_sl.dart | 5 +- lib/l10n/app_localizations_sv.dart | 5 +- lib/l10n/app_localizations_uk.dart | 5 +- lib/l10n/app_localizations_zh.dart | 5 +- lib/screens/channels_screen.dart | 7 ++ lib/storage/channel_message_store.dart | 16 +++ test/connector/channel_write_reread_test.dart | 91 +++++++++++++++++ test/helpers/channel_slot_ui_test.dart | 58 +++++++++-- untranslated.json | 17 ++++ 27 files changed, 401 insertions(+), 35 deletions(-) create mode 100644 test/connector/channel_write_reread_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index da1b0b91..754b7e18 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -670,6 +670,10 @@ class MeshCoreConnector extends ChangeNotifier { // Channel syncing state (sequential pattern) bool _isSyncingChannels = false; + + /// Completes when the running channel sync ends: true if every slot was + /// read, false if it failed. Null when no sync is running (#1163). + Completer? _channelSyncDone; bool _channelSyncInFlight = false; Timer? _channelSyncTimeout; Timer? _channelsChangedDebounce; @@ -7100,6 +7104,7 @@ class MeshCoreConnector extends ChangeNotifier { _isLoadingChannels = true; _isSyncingChannels = true; + _channelSyncDone = Completer(); _hasLoadedChannels = false; // Re-engage the ingress barrier for the duration of the sync: filing // against a list that is mid-replacement is the same hazard as filing @@ -7430,6 +7435,9 @@ class MeshCoreConnector extends ChangeNotifier { void _cleanupChannelSync({required bool completed}) { _isSyncingChannels = false; + final done = _channelSyncDone; + _channelSyncDone = null; + if (done != null && !done.isCompleted) done.complete(completed); _channelSyncInFlight = false; _isLoadingChannels = false; _channelSyncTimeout?.cancel(); @@ -7609,13 +7617,72 @@ class MeshCoreConnector extends ChangeNotifier { bool refresh = true, }) async { if (!isConnected) return ChannelWrite.noReply; - return _setChannel( + final occupantPsk = _findChannelByIndex(index)?.psk; + final result = await _setChannel( index, name, psk, - occupantPsk: _findChannelByIndex(index)?.psk, + occupantPsk: occupantPsk, refresh: refresh, ); + if (result != ChannelWrite.noReply || !refresh) return result; + final landed = await _rereadConfirms( + index, + 'write', + (slot) => slot != null && slot.name == name && listEquals(slot.psk, psk), + ); + if (!landed) return result; + if (occupantPsk == null || !listEquals(occupantPsk, psk)) { + await _retireSlotOccupant(index); + } + return ChannelWrite.ok; + } + + /// After a write the radio did not answer: waits for the re-read the write + /// asked for, and says whether slot [index] now holds what was written. + /// + /// A lost reply does not mean a lost write. Saying "the radio did not + /// confirm" when the channel is in fact there sends the user to fix + /// something that is not broken, so the error is shown only when the re-read + /// still disagrees, or could not finish (#1163). + Future _rereadConfirms( + int index, + String what, + bool Function(Channel? slot) holdsTheChange, + ) async { + final done = _channelSyncDone; + if (done == null) return false; + final complete = await done.future.timeout( + const Duration(seconds: 30), + onTimeout: () => false, + ); + if (!complete || _unconfirmedChannelSlots.contains(index)) { + _appDebugLogService?.warn( + 'Channel $what to slot $index got no reply, and the re-read could not ' + 'confirm the slot either', + tag: 'ChannelWrite', + ); + return false; + } + final slot = _channels.cast().firstWhere( + (c) => c?.index == index, + orElse: () => null, + ); + final landed = holdsTheChange(slot); + if (landed) { + _appDebugLogService?.info( + 'Channel $what to slot $index got no reply, but the re-read shows it ' + 'landed; reporting it as done', + tag: 'ChannelWrite', + ); + } else { + _appDebugLogService?.warn( + 'Channel $what to slot $index got no reply, and the re-read shows it ' + 'did not land (slot holds "${slot?.name ?? ''}")', + tag: 'ChannelWrite', + ); + } + return landed; } /// Writes an edit of [channel]. A rename keeps the key and is a plain write. @@ -7693,6 +7760,32 @@ class MeshCoreConnector extends ChangeNotifier { Future deleteChannel(int index, {bool refresh = true}) async { if (!isConnected) return ChannelWrite.noReply; + final victimPskHex = _findChannelByIndex(index)?.pskHex; + final result = await _deleteChannel(index, refresh: refresh); + if (result != ChannelWrite.noReply || !refresh) return result; + final landed = await _rereadConfirms( + index, + 'delete', + (slot) => slot == null || slot.isEmpty, + ); + if (!landed) return result; + // The slot is empty now, so it no longer resolves to the deleted channel: + // clear that channel's history by its own key. + if (victimPskHex != null) { + await _channelMessageStore.clearChannelMessagesForPsk( + victimPskHex, + index, + ); + } + _channelMessages.remove(index); + _windowPskHex.remove(index); + return ChannelWrite.ok; + } + + Future _deleteChannel( + int index, { + required bool refresh, + }) async { _beginChannelWrite(); try { // A slot is deleted by writing an empty name and a zero PSK. Its history diff --git a/lib/helpers/channel_slot_ui.dart b/lib/helpers/channel_slot_ui.dart index 4bfa822b..7e28e4ce 100644 --- a/lib/helpers/channel_slot_ui.dart +++ b/lib/helpers/channel_slot_ui.dart @@ -1,6 +1,8 @@ +import 'dart:async'; import 'dart:typed_data'; import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; import '../connector/meshcore_connector.dart'; import '../l10n/l10n.dart'; @@ -88,10 +90,48 @@ bool explainUnconfirmedChannelWrite(BuildContext context, ChannelWrite result) { ChannelWrite.historyNotMoved => l10n.channels_writeHistoryNotMoved, }; if (message == null) return false; - showChannelBlockedMessage(context, message); + if (result == ChannelWrite.noReply) { + showChannelErrorWithResync(context, message); + } else { + showChannelBlockedMessage(context, message); + } return true; } +/// A persistent channel error with a Resync button, for when the channel list +/// itself is in doubt. The message names the fix; the button is the fix +/// (#1163). +void showChannelErrorWithResync(BuildContext context, String message) { + final connector = context.read(); + showDismissibleSnackBar( + context, + persist: true, + content: Row( + children: [ + Expanded(child: Text(message)), + TextButton( + onPressed: () => resyncChannels(context, connector), + child: Text(context.l10n.channels_resync), + ), + ], + ), + ); +} + +/// Re-reads every channel slot from the radio, or says why it cannot right +/// now. Never a silent no-op: a sync already running is the only refusal, and +/// it is explained (#1163). +void resyncChannels(BuildContext context, MeshCoreConnector connector) { + if (connector.isChannelTableBusy) { + // The toast holding the button can outlive the screen that showed it. + if (context.mounted) { + showChannelBlockedMessage(context, context.l10n.channels_slotBusySyncing); + } + return; + } + unawaited(connector.getChannels(force: true)); +} + /// Asks what a key change does with [channelName]'s message history: kept /// under the new key, or deleted. Null means the user backed out, and nothing /// may be written (#1128). diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index b2f3fda3..fb011d0f 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -885,6 +885,10 @@ } }, "channels_retrySync": "Retry sync", + "channels_resync": "Resync channels", + "@channels_resync": { + "description": "Re-reads every channel slot from the radio. App bar action on the Channels screen, and the button on a channel error (#1163)." + }, "channels_erasedSlots": "The radio has lost the channels in slot(s) {slots}; it reported them as erased. Your channel list here has been kept and was not overwritten.", "@channels_erasedSlots": { "placeholders": { @@ -1085,9 +1089,9 @@ "@channels_writeRejected": { "description": "The radio answered a channel write with an error other than slot-occupied. Persistent (#1026)." }, - "channels_writeNoReply": "The radio did not confirm the change. Check the channel list before trying again.", + "channels_writeNoReply": "The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.", "@channels_writeNoReply": { - "description": "A channel write got no reply before the timeout, or the radio is not connected; it may or may not have landed. Persistent (#1026)." + "description": "A channel write got no reply, and the automatic re-read of the radio's channels did not show the change (or could not finish), or the radio is not connected. Persistent, with a Resync button (#1026, #1163)." }, "channels_writeClearedNotAdded": "The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.", "@channels_writeClearedNotAdded": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index cd0b9837..611035f9 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2986,6 +2986,12 @@ abstract class AppLocalizations { /// **'Retry sync'** String get channels_retrySync; + /// Re-reads every channel slot from the radio. App bar action on the Channels screen, and the button on a channel error (#1163). + /// + /// In en, this message translates to: + /// **'Resync channels'** + String get channels_resync; + /// No description provided for @channels_erasedSlots. /// /// In en, this message translates to: @@ -3370,10 +3376,10 @@ abstract class AppLocalizations { /// **'The radio refused the change, so the channel is as it was.'** String get channels_writeRejected; - /// A channel write got no reply before the timeout, or the radio is not connected; it may or may not have landed. Persistent (#1026). + /// A channel write got no reply, and the automatic re-read of the radio's channels did not show the change (or could not finish), or the radio is not connected. Persistent, with a Resync button (#1026, #1163). /// /// In en, this message translates to: - /// **'The radio did not confirm the change. Check the channel list before trying again.'** + /// **'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'** String get channels_writeNoReply; /// A channel key change is clear-then-add; the clear landed and the add did not, so the edited channel is gone from the radio. Persistent (#1026). diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 16074096..317f1e05 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1683,6 +1683,9 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1927,7 +1930,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 86d2d4ac..89787bd8 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1677,6 +1677,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1922,7 +1925,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index c31afc87..eede4d4f 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1659,6 +1659,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1900,7 +1903,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 4a731d04..7332cebd 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1678,6 +1678,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1923,7 +1926,7 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index ca1692eb..1ea280dc 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1683,6 +1683,9 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1928,7 +1931,7 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index f8276eeb..210d4815 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1684,6 +1684,9 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1928,7 +1931,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index aa91e014..7693f204 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1679,6 +1679,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1925,7 +1928,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index e7acd1d5..5b985728 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1627,6 +1627,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1866,7 +1869,7 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 0739a01d..c666fac2 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1622,6 +1622,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1861,7 +1864,7 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index f54677a7..d83a19b9 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1670,6 +1670,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1913,7 +1916,7 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 455aa673..19daf705 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1689,6 +1689,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1934,7 +1937,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index c46b31ee..3bc8222a 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1679,6 +1679,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1922,7 +1925,7 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index a9332831..88352185 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1680,6 +1680,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1923,7 +1926,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 18142185..afba107c 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1670,6 +1670,9 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1914,7 +1917,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index f2ea851f..54b9b46e 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1667,6 +1667,9 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1911,7 +1914,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 84f5f16a..3591fa90 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1661,6 +1661,9 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1903,7 +1906,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 2877c165..047638eb 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1675,6 +1675,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1918,7 +1921,7 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index d23c2d3d..3a786551 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1608,6 +1608,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String get channels_resync => 'Resync channels'; + @override String channels_erasedSlots(String slots) { return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; @@ -1847,7 +1850,7 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_writeNoReply => - 'The radio did not confirm the change. Check the channel list before trying again.'; + 'The radio did not confirm the change, and re-reading its channels did not show it either. Resync, then check the list before trying again.'; @override String get channels_writeClearedNotAdded => diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index f26888a8..789c540b 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -123,6 +123,13 @@ class _ChannelsScreenState extends State centerTitle: true, bottom: const SyncProgressAppBarBottom(), actions: [ + // #1163: resync was reachable only by pulling the list down, which + // nothing on screen said, while errors told the user to resync. + IconButton( + icon: const Icon(Icons.sync), + tooltip: context.l10n.channels_resync, + onPressed: () => resyncChannels(context, connector), + ), // Disconnect and Settings moved to the panel footer (#290); only // the screen-level Communities entry remains, and it already only // appears once a community has been joined. diff --git a/lib/storage/channel_message_store.dart b/lib/storage/channel_message_store.dart index 04e92f76..91ad917f 100644 --- a/lib/storage/channel_message_store.dart +++ b/lib/storage/channel_message_store.dart @@ -391,6 +391,22 @@ class ChannelMessageStore { } } + /// [clearChannelMessages] for a channel that no longer occupies its slot: + /// the history under [pskHex] and the slot's raw index key. For a delete the + /// radio confirmed only on a re-read, when the slot already resolves to + /// nothing (#1163). + Future clearChannelMessagesForPsk( + String pskHex, + int channelIndex, + ) async { + if (publicKeyHex.isEmpty || pskHex.isEmpty) return; + final blobs = BlobStore.instance; + for (final key in {_pskKey(pskHex), _indexKey(channelIndex)}) { + await blobs.deleteEverywhere(key); + await blobs.deleteMessageRows(key); + } + } + /// Purges only the LEGACY slot-keyed history for [channelIndex]: the /// device-scoped index key and the pre-device-scoping unscoped key. Used /// when a slot is reassigned to a different channel (#193): without this, diff --git a/test/connector/channel_write_reread_test.dart b/test/connector/channel_write_reread_test.dart new file mode 100644 index 00000000..48791851 --- /dev/null +++ b/test/connector/channel_write_reread_test.dart @@ -0,0 +1,91 @@ +// #1163: a channel write the radio did not answer is checked against a re-read +// before the user is told it was not confirmed. A lost reply is not a lost +// write; the owner was sent to fix channels that were in fact fine. + +import 'dart:typed_data'; + +import 'package:drift/native.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/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 _psk(int fill) => Uint8List.fromList(List.filled(16, fill)); + +List _channelInfo(int index, String name, Uint8List psk) => [ + respCodeChannelInfo, + index, + ...name.codeUnits, + ...List.filled(32 - name.length, 0), + ...psk, +]; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late OffbandDatabase db; + late MeshCoreConnector c; + + // What the fake radio holds per slot. It answers every channel read and + // never answers a channel write: the reply was lost. + late Map radio; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + radio = {}; + c = MeshCoreConnector(); + c.setConnectedForTest(); + c.channelWriteReplyTimeout = const Duration(milliseconds: 20); + c.sendFrameOverrideForTest = (frame) { + if (frame.isEmpty || frame[0] != cmdGetChannel) return; + final index = frame[1]; + final (name, psk) = radio[index] ?? ('', Uint8List(16)); + Future.microtask( + () => c.handleFrameForTest(_channelInfo(index, name, psk)), + ); + }; + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + group('an add with no reply', () { + test('is reported done when the re-read shows the channel', () async { + radio[3] = ('Weather', _psk(0x22)); // the write landed + + final result = await c.setChannel(3, 'Weather', _psk(0x22)); + + expect(result, ChannelWrite.ok); + }); + + test('is still not confirmed when the re-read does not show it', () async { + final result = await c.setChannel(3, 'Weather', _psk(0x22)); + + expect(result, ChannelWrite.noReply); + }); + }); + + group('a delete with no reply', () { + test('is reported done when the re-read shows the slot empty', () async { + final result = await c.deleteChannel(3); + + expect(result, ChannelWrite.ok); + }); + + test('is still not confirmed when the channel is still there', () async { + radio[3] = ('Weather', _psk(0x22)); + + final result = await c.deleteChannel(3); + + expect(result, ChannelWrite.noReply); + }); + }); +} diff --git a/test/helpers/channel_slot_ui_test.dart b/test/helpers/channel_slot_ui_test.dart index 88d072ef..090bb3eb 100644 --- a/test/helpers/channel_slot_ui_test.dart +++ b/test/helpers/channel_slot_ui_test.dart @@ -11,6 +11,7 @@ import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/helpers/channel_slot_ui.dart'; import 'package:meshcore_open/l10n/app_localizations.dart'; import 'package:meshcore_open/models/channel.dart'; +import 'package:provider/provider.dart'; class _FakeConn extends MeshCoreConnector { _FakeConn({this.list = const [], this.max = 40, this.busy = false}); @@ -18,6 +19,7 @@ class _FakeConn extends MeshCoreConnector { final List list; final int max; final bool busy; + int resyncs = 0; @override List get channels => list; @@ -25,6 +27,10 @@ class _FakeConn extends MeshCoreConnector { int get maxChannels => max; @override bool get isChannelTableBusy => busy; + @override + Future getChannels({int? maxChannels, bool force = false}) async { + if (force) resyncs++; + } } Channel _ch(int index, String name, int fill) => Channel( @@ -50,18 +56,21 @@ final _allMessages = [ _l10n.channels_writeClearedNotAdded, ]; -Future _host(WidgetTester tester) async { +Future _host(WidgetTester tester, [_FakeConn? conn]) async { late BuildContext context; await tester.pumpWidget( - MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold( - body: Builder( - builder: (c) { - context = c; - return const SizedBox.shrink(); - }, + ChangeNotifierProvider.value( + value: conn ?? _FakeConn(), + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (c) { + context = c; + return const SizedBox.shrink(); + }, + ), ), ), ), @@ -248,6 +257,35 @@ void main() { expect(explainUnconfirmedChannelWrite(context, ChannelWrite.ok), isFalse); await _expectNoRefusal(tester); }); + + // #1163: the message said to resync and offered no way to. + testWidgets('noReply: its Resync button re-reads the channels', ( + tester, + ) async { + final conn = _FakeConn(); + final context = await _host(tester, conn); + + explainUnconfirmedChannelWrite(context, ChannelWrite.noReply); + await tester.pump(); + await tester.tap(find.text(_l10n.channels_resync)); + await tester.pump(); + + expect(conn.resyncs, 1); + }); + + testWidgets('noReply: Resync during a sync says so instead', ( + tester, + ) async { + final conn = _FakeConn(busy: true); + final context = await _host(tester, conn); + + explainUnconfirmedChannelWrite(context, ChannelWrite.noReply); + await tester.pump(); + await tester.tap(find.text(_l10n.channels_resync)); + + expect(conn.resyncs, 0); + await _expectPersistent(tester, _l10n.channels_slotBusySyncing); + }); }); group('refuseWhileChannelTableBusy', () { diff --git a/untranslated.json b/untranslated.json index 0bce3ab7..c7cabcf6 100644 --- a/untranslated.json +++ b/untranslated.json @@ -154,6 +154,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -554,6 +555,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -954,6 +956,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -1354,6 +1357,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -1754,6 +1758,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -2154,6 +2159,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -2554,6 +2560,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -2954,6 +2961,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -3354,6 +3362,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -3754,6 +3763,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -4154,6 +4164,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -4554,6 +4565,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -4954,6 +4966,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -5354,6 +5367,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -5754,6 +5768,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -6154,6 +6169,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", @@ -6554,6 +6570,7 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_resync", "channels_erasedSlots", "channels_restoreToRadio", "channels_restoreToRadioConfirm", From bc625458d118ea62ee1056f0ac0e27dad48bd4f4 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:00:08 -0500 Subject: [PATCH 5/7] feat(#1163): delete a radio's message history; Clear Chat deletes Settings > Actions gets "Delete message history": the connected radio's channel messages and direct messages, removed from the app after a red confirm. Contacts, channels and settings stay. The owner's ruling: start fresh for a radio, channels and DMs together. Clear Chat on a channel or a contact saved the emptied list. Saves merge since #343, so that deleted nothing and the history came back on the next load. Both now confirm in red and delete the stored history, the channel's by its own PSK. Co-Authored-By: Claude Opus 5.5 --- lib/connector/meshcore_connector.dart | 78 ++++++-- lib/l10n/app_en.arb | 26 +++ lib/l10n/app_localizations.dart | 54 ++++++ lib/l10n/app_localizations_bg.dart | 36 ++++ lib/l10n/app_localizations_de.dart | 36 ++++ lib/l10n/app_localizations_en.dart | 36 ++++ lib/l10n/app_localizations_es.dart | 36 ++++ lib/l10n/app_localizations_fr.dart | 36 ++++ lib/l10n/app_localizations_hu.dart | 36 ++++ lib/l10n/app_localizations_it.dart | 36 ++++ lib/l10n/app_localizations_ja.dart | 36 ++++ lib/l10n/app_localizations_ko.dart | 36 ++++ lib/l10n/app_localizations_nl.dart | 36 ++++ lib/l10n/app_localizations_pl.dart | 36 ++++ lib/l10n/app_localizations_pt.dart | 36 ++++ lib/l10n/app_localizations_ru.dart | 36 ++++ lib/l10n/app_localizations_sk.dart | 36 ++++ lib/l10n/app_localizations_sl.dart | 36 ++++ lib/l10n/app_localizations_sv.dart | 36 ++++ lib/l10n/app_localizations_uk.dart | 36 ++++ lib/l10n/app_localizations_zh.dart | 36 ++++ lib/screens/channel_chat_screen.dart | 19 +- lib/screens/chat_screen.dart | 16 +- lib/screens/settings_screen.dart | 34 ++++ lib/storage/radio_data_wipe.dart | 36 ++++ lib/utils/dialog_utils.dart | 32 ++++ test/screens/settings_declutter_test.dart | 6 +- test/storage/message_history_wipe_test.dart | 192 ++++++++++++++++++++ untranslated.json | 153 ++++++++++++++++ 29 files changed, 1278 insertions(+), 16 deletions(-) create mode 100644 test/storage/message_history_wipe_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 754b7e18..8cd9824a 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -309,6 +309,9 @@ enum ContactKeyCheckResult { onRadio, notFound, unresolved } /// Why a factory reset was not sent. (#1054) enum FactoryResetRefusal { notConnected } +/// Why a radio's message history was not deleted. (#1163) +enum HistoryWipeRefusal { notConnected, failed } + /// Where a factory reset stands, for the app-wide banner. (#1054) enum FactoryResetStatus { /// Sent. Over BLE the radio's pairing is gone too, so the OS one must go. @@ -3933,6 +3936,7 @@ class MeshCoreConnector extends ChangeNotifier { @visibleForTesting void wireMessageStoreForTest() { _channelMessageStore.setPublicKeyHex = selfPublicKeyHex; + _messageStore.setPublicKeyHex = selfPublicKeyHex; _channelMessageStore.channelPskResolver = (index) => _findChannelByIndex(index)?.pskHex; } @@ -12705,25 +12709,77 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } - void clearMessagesForContact(Contact contact) { + /// Deletes the stored direct messages with [contact] and empties them on + /// screen. Saving the emptied list, which this used to do, deleted nothing + /// once saves merged (#343): the conversation came back (#1163). + Future clearMessagesForContact(Contact contact) async { final contactKeyHex = contact.publicKeyHex; - final messages = _conversations[contactKeyHex]; - if (messages == null) return; - messages.clear(); - unawaited(_messageStore.saveMessages(contactKeyHex, messages)); + await _messageStore.clearMessages(contactKeyHex); + _conversations[contactKeyHex]?.clear(); markContactRead(contactKeyHex); notifyListeners(); } - void clearMessagesForChannel(int channelIndex) { - final messages = _channelMessages[channelIndex]; - if (messages == null) return; - messages.clear(); - unawaited(_channelMessageStore.saveChannelMessages(channelIndex, messages)); - markChannelRead(channelIndex); + /// Deletes [channel]'s stored message history, by its own key, and empties + /// it on screen (#1163). + /// + /// This used to save the emptied window, and since saves merge (#343) that + /// deleted nothing: the history came back on the next load. + Future clearChannelHistory(Channel channel) async { + await _channelMessageStore.clearChannelMessagesForPsk( + channel.pskHex, + channel.index, + ); + _channelMessages.remove(channel.index); + _windowPskHex.remove(channel.index); + markChannelRead(channel.index); + _appDebugLogService?.info( + 'Cleared channel history: radio ' + '${AppSettingsService.radioScopePrefix(selfPublicKeyHex)} slot ' + '${channel.index} "${channel.name}" psk ' + '${AppSettingsService.pskFingerprint(channel.pskHex)} (#1163)', + tag: 'Storage', + ); notifyListeners(); } + /// Deletes the connected radio's message history, channel messages and + /// direct messages, and empties both on screen. Contacts, channels and + /// settings stay (#1163). Null when done; otherwise why it was not. + Future deleteMessageHistoryForThisRadio() async { + final prefix = _channelMessageStore.publicKeyHex; + if (!isConnected || prefix.isEmpty) { + return HistoryWipeRefusal.notConnected; + } + final int removed; + try { + removed = await wipeRadioMessageHistory(prefix); + } catch (e) { + _appDebugLogService?.error( + 'Deleting message history for radio $prefix failed: $e (#1163)', + tag: 'Storage', + ); + return HistoryWipeRefusal.failed; + } + _channelMessages.clear(); + _windowPskHex.clear(); + _conversations.clear(); + _loadedConversationKeys.clear(); + for (final channel in List.of(_channels)) { + markChannelRead(channel.index); + } + for (final key in List.of(_contactUnreadCount.keys)) { + markContactRead(key); + } + _appDebugLogService?.info( + 'Deleted message history for radio $prefix: $removed key(s) and row ' + 'group(s), channels and direct messages (#1163)', + tag: 'Storage', + ); + notifyListeners(); + return null; + } + void deleteAllPaths() { _pathHistoryService?.clearAllHistories(); } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index fb011d0f..8cefe9e5 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -438,6 +438,32 @@ "settings_factoryResetConfirm": "This erases everything on the radio: its identity, contacts, channels and settings. It can't be undone.", "settings_factoryResetDeleteAppData": "Also delete this radio's data stored in the app", "settings_factoryResetNotConnected": "Factory reset not sent: no radio is connected.", + "settings_deleteMessageHistory": "Delete message history", + "@settings_deleteMessageHistory": { + "description": "Settings action: deletes the connected radio's channel and direct message history stored in the app (#1163)." + }, + "settings_deleteMessageHistorySubtitle": "Start fresh: remove this radio's channel and direct messages from the app", + "settings_deleteMessageHistoryConfirm": "This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can't be undone.", + "settings_deleteMessageHistoryDone": "Message history deleted for this radio.", + "settings_deleteMessageHistoryNotConnected": "Message history not deleted: no radio is connected.", + "settings_deleteMessageHistoryFailed": "Some or all of this radio's message history could not be deleted. The app log has the details.", + "chat_clearHistoryTitle": "Clear message history?", + "chat_clearChannelHistoryConfirm": "Delete every message stored in {channel} for this radio? It can't be undone.", + "@chat_clearChannelHistoryConfirm": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "chat_clearContactHistoryConfirm": "Delete every message stored with {name} for this radio? It can't be undone.", + "@chat_clearContactHistoryConfirm": { + "placeholders": { + "name": { + "type": "String" + } + } + }, "factoryResetSentTitle": "Factory reset sent", "factoryResetSentBody": "The radio is erasing itself and will restart with a new identity.", "factoryResetSentBleBody": "The radio is erasing itself and will restart with a new identity. Its Bluetooth pairing is erased too: remove the old pairing for this radio in your phone or computer's Bluetooth settings, then reconnect.", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 611035f9..79c3aa4f 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -1516,6 +1516,60 @@ abstract class AppLocalizations { /// **'Factory reset not sent: no radio is connected.'** String get settings_factoryResetNotConnected; + /// Settings action: deletes the connected radio's channel and direct message history stored in the app (#1163). + /// + /// In en, this message translates to: + /// **'Delete message history'** + String get settings_deleteMessageHistory; + + /// No description provided for @settings_deleteMessageHistorySubtitle. + /// + /// In en, this message translates to: + /// **'Start fresh: remove this radio\'s channel and direct messages from the app'** + String get settings_deleteMessageHistorySubtitle; + + /// No description provided for @settings_deleteMessageHistoryConfirm. + /// + /// In en, this message translates to: + /// **'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'** + String get settings_deleteMessageHistoryConfirm; + + /// No description provided for @settings_deleteMessageHistoryDone. + /// + /// In en, this message translates to: + /// **'Message history deleted for this radio.'** + String get settings_deleteMessageHistoryDone; + + /// No description provided for @settings_deleteMessageHistoryNotConnected. + /// + /// In en, this message translates to: + /// **'Message history not deleted: no radio is connected.'** + String get settings_deleteMessageHistoryNotConnected; + + /// No description provided for @settings_deleteMessageHistoryFailed. + /// + /// In en, this message translates to: + /// **'Some or all of this radio\'s message history could not be deleted. The app log has the details.'** + String get settings_deleteMessageHistoryFailed; + + /// No description provided for @chat_clearHistoryTitle. + /// + /// In en, this message translates to: + /// **'Clear message history?'** + String get chat_clearHistoryTitle; + + /// No description provided for @chat_clearChannelHistoryConfirm. + /// + /// In en, this message translates to: + /// **'Delete every message stored in {channel} for this radio? It can\'t be undone.'** + String chat_clearChannelHistoryConfirm(String channel); + + /// No description provided for @chat_clearContactHistoryConfirm. + /// + /// In en, this message translates to: + /// **'Delete every message stored with {name} for this radio? It can\'t be undone.'** + String chat_clearContactHistoryConfirm(String name); + /// No description provided for @factoryResetSentTitle. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 317f1e05..e96c9f76 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -828,6 +828,42 @@ class AppLocalizationsBg extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 89787bd8..dea37c84 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -825,6 +825,42 @@ class AppLocalizationsDe extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index eede4d4f..47d5a99d 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -816,6 +816,42 @@ class AppLocalizationsEn extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 7332cebd..9a210b8d 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -826,6 +826,42 @@ class AppLocalizationsEs extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 1ea280dc..dc94318f 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -830,6 +830,42 @@ class AppLocalizationsFr extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 210d4815..a9533a8a 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -828,6 +828,42 @@ class AppLocalizationsHu extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 7693f204..8b67ac65 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -828,6 +828,42 @@ class AppLocalizationsIt extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 5b985728..338c7c69 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -802,6 +802,42 @@ class AppLocalizationsJa extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index c666fac2..ca35dda6 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -802,6 +802,42 @@ class AppLocalizationsKo extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index d83a19b9..1a28d669 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -822,6 +822,42 @@ class AppLocalizationsNl extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 19daf705..e7163726 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -830,6 +830,42 @@ class AppLocalizationsPl extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 3bc8222a..15bbf03f 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -828,6 +828,42 @@ class AppLocalizationsPt extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 88352185..0613ade1 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -827,6 +827,42 @@ class AppLocalizationsRu extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index afba107c..25f92a1b 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -822,6 +822,42 @@ class AppLocalizationsSk extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 54b9b46e..a2fca70a 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -820,6 +820,42 @@ class AppLocalizationsSl extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 3591fa90..08f7e6c1 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -817,6 +817,42 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 047638eb..f565d202 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -824,6 +824,42 @@ class AppLocalizationsUk extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 3a786551..c37d9022 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -795,6 +795,42 @@ class AppLocalizationsZh extends AppLocalizations { String get settings_factoryResetNotConnected => 'Factory reset not sent: no radio is connected.'; + @override + String get settings_deleteMessageHistory => 'Delete message history'; + + @override + String get settings_deleteMessageHistorySubtitle => + 'Start fresh: remove this radio\'s channel and direct messages from the app'; + + @override + String get settings_deleteMessageHistoryConfirm => + 'This deletes every channel message and direct message this app has stored for this radio. Contacts, channels and settings stay. It can\'t be undone.'; + + @override + String get settings_deleteMessageHistoryDone => + 'Message history deleted for this radio.'; + + @override + String get settings_deleteMessageHistoryNotConnected => + 'Message history not deleted: no radio is connected.'; + + @override + String get settings_deleteMessageHistoryFailed => + 'Some or all of this radio\'s message history could not be deleted. The app log has the details.'; + + @override + String get chat_clearHistoryTitle => 'Clear message history?'; + + @override + String chat_clearChannelHistoryConfirm(String channel) { + return 'Delete every message stored in $channel for this radio? It can\'t be undone.'; + } + + @override + String chat_clearContactHistoryConfirm(String name) { + return 'Delete every message stored with $name for this radio? It can\'t be undone.'; + } + @override String get factoryResetSentTitle => 'Factory reset sent'; diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 8bf99eb9..6b8a22e0 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -330,6 +330,21 @@ class _ChannelChatScreenState extends State { } /// Open the Set Region Scope picker for the current channel (#815). + /// Clear Chat deletes the stored history after a red confirm. It used to + /// empty the screen only, and the history came back on the next load (#1163). + Future _confirmClearHistory(BuildContext context) async { + final l10n = context.l10n; + final connector = context.read(); + final channel = _currentChannel; + final confirmed = await confirmDelete( + context, + title: l10n.chat_clearHistoryTitle, + body: l10n.chat_clearChannelHistoryConfirm(channel.name), + ); + if (!confirmed) return; + await connector.clearChannelHistory(channel); + } + Future _openRegionScopeDialog() async { final connector = context.read(); final channelIndex = _currentChannel.index; @@ -486,9 +501,7 @@ class _ChannelChatScreenState extends State { requestChannelRadioTone(connector, _currentChannel.index); showChannelRadioToneDialog(context, _currentChannel); } else if (value == 'clearChat') { - context.read().clearMessagesForChannel( - _currentChannel.index, - ); + unawaited(_confirmClearHistory(context)); } else if (value == 'setRegionScope') { _openRegionScopeDialog(); } diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 8f4787da..996aeb0f 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -52,6 +52,7 @@ import '../widgets/sync_progress_overlay.dart'; import '../widgets/translated_message_content.dart'; import '../utils/app_logger.dart'; import '../l10n/l10n.dart'; +import '../utils/dialog_utils.dart'; import '../helpers/snack_bar_builder.dart'; import '../widgets/unread_divider.dart'; import 'telemetry_screen.dart'; @@ -364,7 +365,20 @@ class _ChatScreenState extends State { ); } if (value == 'clearChat') { - connector.clearMessagesForContact(widget.contact); + // #1163: a red confirm, then a real delete. This used to + // empty the screen only; the history came back on reload. + unawaited(() async { + final confirmed = await confirmDelete( + context, + title: context.l10n.chat_clearHistoryTitle, + body: context.l10n.chat_clearContactHistoryConfirm( + widget.contact.name, + ), + ); + if (confirmed) { + await connector.clearMessagesForContact(widget.contact); + } + }()); } if (value == 'block') { context.read().block( diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index beefeb89..eff801b7 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1,5 +1,7 @@ import 'dart:async'; +import '../utils/dialog_utils.dart'; + import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -876,6 +878,13 @@ class _SettingsScreenState extends State { onTap: () => _confirmReboot(context, connector), ), const Divider(height: 1), + ListTile( + leading: const Icon(Icons.delete_sweep_outlined, color: Colors.red), + title: Text(l10n.settings_deleteMessageHistory), + subtitle: Text(l10n.settings_deleteMessageHistorySubtitle), + onTap: () => unawaited(_confirmDeleteMessageHistory(connector)), + ), + const Divider(height: 1), ListTile( leading: const Icon(Icons.delete_forever, color: Colors.red), title: Text(l10n.settings_factoryReset), @@ -1294,6 +1303,31 @@ class _SettingsScreenState extends State { ); } + /// #1163: start fresh for this radio. Channels and direct messages together + /// (owner, 2026-11-19); contacts, channels and settings stay. + Future _confirmDeleteMessageHistory(MeshCoreConnector connector) async { + final l10n = context.l10n; + final confirmed = await confirmDelete( + context, + title: l10n.settings_deleteMessageHistory, + body: l10n.settings_deleteMessageHistoryConfirm, + ); + if (!confirmed) return; + final refusal = await connector.deleteMessageHistoryForThisRadio(); + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(switch (refusal) { + null => l10n.settings_deleteMessageHistoryDone, + HistoryWipeRefusal.notConnected => + l10n.settings_deleteMessageHistoryNotConnected, + HistoryWipeRefusal.failed => l10n.settings_deleteMessageHistoryFailed, + }), + backgroundColor: refusal == null ? null : Colors.red, + persist: refusal != null, + ); + } + void _confirmFactoryReset(BuildContext context, MeshCoreConnector connector) { final l10n = context.l10n; var deleteAppData = true; diff --git a/lib/storage/radio_data_wipe.dart b/lib/storage/radio_data_wipe.dart index 9e01d078..7dbede05 100644 --- a/lib/storage/radio_data_wipe.dart +++ b/lib/storage/radio_data_wipe.dart @@ -47,3 +47,39 @@ Future wipeRadioData(String radioPrefix) async { return removed; } + +/// Deletes one radio's message history, its channel messages and its direct +/// messages, and nothing else: contacts, channels and settings stay (#1163). +/// +/// For a history that is already mixed up. The owner's ruling: start fresh +/// for that radio, channels and DMs together. Same prefix rule and the same +/// refusal of anything but a 10-hex prefix as [wipeRadioData]. +/// +/// Returns how many keys and row groups were removed. +Future wipeRadioMessageHistory(String radioPrefix) async { + if (!RegExp(r'^[0-9a-f]{10}$').hasMatch(radioPrefix)) { + throw ArgumentError.value( + radioPrefix, + 'radioPrefix', + 'must be the 10-hex radio key prefix', + ); + } + + final blobs = BlobStore.instance; + final prefixes = ['channel_messages_$radioPrefix', 'messages_$radioPrefix']; + + var removed = 0; + for (final prefix in prefixes) { + for (final key in await blobs.keysWithPrefix(prefix)) { + await blobs.deleteEverywhere(key); + removed++; + } + } + for (final storeKey in await blobs.messageStoreKeys()) { + if (prefixes.any(storeKey.startsWith)) { + await blobs.deleteMessageRows(storeKey); + removed++; + } + } + return removed; +} diff --git a/lib/utils/dialog_utils.dart b/lib/utils/dialog_utils.dart index 8a6ad9bb..ff05e240 100644 --- a/lib/utils/dialog_utils.dart +++ b/lib/utils/dialog_utils.dart @@ -35,3 +35,35 @@ Future showDisconnectDialog( } return false; } + +/// Asks before deleting something that cannot be undone. The confirming button +/// is red, as Reboot and Factory Reset are. True only on an explicit confirm. +Future confirmDelete( + BuildContext context, { + required String title, + required String body, + String? action, +}) async { + final l10n = context.l10n; + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(title), + content: Text(body), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(l10n.common_cancel), + ), + TextButton( + onPressed: () => Navigator.pop(dialogContext, true), + child: Text( + action ?? l10n.common_delete, + style: const TextStyle(color: Colors.red), + ), + ), + ], + ), + ); + return confirmed == true; +} diff --git a/test/screens/settings_declutter_test.dart b/test/screens/settings_declutter_test.dart index fad53b64..5f98f707 100644 --- a/test/screens/settings_declutter_test.dart +++ b/test/screens/settings_declutter_test.dart @@ -40,7 +40,9 @@ void main() { Future pumpSettings(WidgetTester tester) async { // Narrow layout: the category list renders and each detail pane builds // lazily when its tile is tapped (so unrelated panes never construct). - tester.view.physicalSize = const Size(400, 900); + // Tall enough that every Actions row builds: the panes are lazy ListViews, + // and #1163's Delete message history row pushed the export card past 900. + tester.view.physicalSize = const Size(400, 1400); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); @@ -84,6 +86,8 @@ void main() { expect(find.byIcon(Icons.download_outlined), findsNWidgets(3)); // The pre-existing Actions still here. expect(find.byIcon(Icons.restart_alt), findsOneWidget); // reboot + // Delete message history for this radio (#1163). + expect(find.byIcon(Icons.delete_sweep_outlined), findsOneWidget); }); testWidgets('Debug keeps only diagnostics, correctly ordered', ( diff --git a/test/storage/message_history_wipe_test.dart b/test/storage/message_history_wipe_test.dart new file mode 100644 index 00000000..4060e3e2 --- /dev/null +++ b/test/storage/message_history_wipe_test.dart @@ -0,0 +1,192 @@ +// #1163: the owner asked for a way to start fresh for one radio, channels and +// direct messages together, and for a channel clear that actually clears. +// Clear Chat used to save an emptied list; saves merge (#343), so nothing was +// deleted and the history came back on the next load. + +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/message.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/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/storage/radio_data_wipe.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +final _radioA = Uint8List.fromList(List.generate(32, (i) => i)); +const _radioAPrefix = '0001020304'; +const _radioBPrefix = '6364656667'; + +Channel _channel(int index, String name, int seed) => Channel( + index: index, + name: name, + psk: Uint8List.fromList(List.generate(16, (i) => (seed + i) & 0xFF)), +); + +ChannelMessage _chanMsg(String text) => ChannelMessage( + senderName: 'X', + text: text, + timestamp: DateTime.fromMillisecondsSinceEpoch(5000), + isOutgoing: false, + status: ChannelMessageStatus.sent, + channelIndex: 0, +); + +Message _dm(String text) => Message( + senderKey: Uint8List(32), + text: text, + timestamp: DateTime.fromMillisecondsSinceEpoch(5000), + isOutgoing: false, +); + +ChannelMessageStore _chanStore(String radio, Channel ch) => + ChannelMessageStore() + ..setPublicKeyHex = radio + ..channelPskResolver = ((_) => ch.pskHex); + +// MessageStore takes the radio's full key and keeps its first 10 hex; a bare +// 10-hex prefix is refused and every save is skipped. +MessageStore _dmStore(String radio) => + MessageStore()..setPublicKeyHex = '$radio${'0' * 54}'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late OffbandDatabase db; + final alpha = _channel(0, 'Alpha', 10); + const contactKey = + 'aa00000000000000000000000000000000000000000000000000000000000000'; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Future> chanTexts(String radio) async => (await _chanStore( + radio, + alpha, + ).loadChannelMessages(0)).map((m) => m.text).toList(); + Future> dmTexts(String radio) async => (await _dmStore( + radio, + ).loadMessages(contactKey)).map((m) => m.text).toList(); + + test("the per-radio wipe removes this radio's channel and DM history, and " + "nothing of any other radio's", () async { + for (final radio in [_radioAPrefix, _radioBPrefix]) { + await _chanStore(radio, alpha).saveChannelMessages(0, [_chanMsg(radio)]); + await _dmStore(radio).saveMessages(contactKey, [_dm(radio)]); + } + await BlobStore.instance.write('contacts$_radioAPrefix', '[]'); + expect(await dmTexts(_radioAPrefix), [_radioAPrefix]); + expect(await dmTexts(_radioBPrefix), [_radioBPrefix]); + + await wipeRadioMessageHistory(_radioAPrefix); + + expect(await chanTexts(_radioAPrefix), isEmpty); + expect(await dmTexts(_radioAPrefix), isEmpty); + expect(await chanTexts(_radioBPrefix), [_radioBPrefix]); + expect(await dmTexts(_radioBPrefix), [_radioBPrefix]); + expect( + await BlobStore.instance.read('contacts$_radioAPrefix'), + '[]', + reason: 'contacts are not message history and stay', + ); + }); + + test('the per-radio wipe refuses anything but a 10-hex radio prefix', () { + expect(() => wipeRadioMessageHistory(''), throwsArgumentError); + expect(() => wipeRadioMessageHistory('0001'), throwsArgumentError); + }); + + group('connector', () { + late MeshCoreConnector c; + + setUp(() { + c = MeshCoreConnector(); + c.setConnectedForTest(); + c.setSelfPublicKeyForTest(_radioA); + c.wireMessageStoreForTest(); + c.seedCachedChannelsForTest([alpha]); + }); + + test( + 'deleting message history for this radio empties the screen too', + () async { + await _chanStore( + _radioAPrefix, + alpha, + ).saveChannelMessages(0, [_chanMsg('old')]); + await c.loadAllChannelMessages(maxChannels: 1); + expect(c.channelMessagesForTest[0], isNotEmpty); + + expect(await c.deleteMessageHistoryForThisRadio(), isNull); + + expect(c.channelMessagesForTest, isEmpty); + expect(await chanTexts(_radioAPrefix), isEmpty); + }, + ); + + test( + 'deleting message history with no radio connected is refused', + () async { + final idle = MeshCoreConnector(); + + expect( + await idle.deleteMessageHistoryForThisRadio(), + HistoryWipeRefusal.notConnected, + ); + }, + ); + + test('Clear Chat on a channel deletes its stored history', () async { + await _chanStore( + _radioAPrefix, + alpha, + ).saveChannelMessages(0, [_chanMsg('old')]); + await c.loadAllChannelMessages(maxChannels: 1); + + await c.clearChannelHistory(alpha); + await c.loadAllChannelMessages(maxChannels: 1); + + expect( + c.channelMessagesForTest[0] ?? const [], + isEmpty, + reason: 'the bug: the history came back on the next load', + ); + expect(await chanTexts(_radioAPrefix), isEmpty); + }); + + test('Clear Chat on a contact deletes the stored conversation', () async { + await _dmStore(_radioAPrefix).saveMessages(contactKey, [_dm('old')]); + expect(await dmTexts(_radioAPrefix), ['old']); + final contact = Contact( + publicKey: Uint8List.fromList( + List.generate(32, (i) => i == 0 ? 0xAA : 0), + ), + receivedName: 'Friend', + type: 1, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + ); + + await c.clearMessagesForContact(contact); + + expect(await dmTexts(_radioAPrefix), isEmpty); + }); + }); +} diff --git a/untranslated.json b/untranslated.json index c7cabcf6..e826c743 100644 --- a/untranslated.json +++ b/untranslated.json @@ -84,6 +84,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -485,6 +494,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -886,6 +904,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -1287,6 +1314,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -1688,6 +1724,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -2089,6 +2134,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -2490,6 +2544,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -2891,6 +2954,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -3292,6 +3364,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -3693,6 +3774,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -4094,6 +4184,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -4495,6 +4594,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -4896,6 +5004,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -5297,6 +5414,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -5698,6 +5824,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -6099,6 +6234,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", @@ -6500,6 +6644,15 @@ "settings_factoryResetConfirm", "settings_factoryResetDeleteAppData", "settings_factoryResetNotConnected", + "settings_deleteMessageHistory", + "settings_deleteMessageHistorySubtitle", + "settings_deleteMessageHistoryConfirm", + "settings_deleteMessageHistoryDone", + "settings_deleteMessageHistoryNotConnected", + "settings_deleteMessageHistoryFailed", + "chat_clearHistoryTitle", + "chat_clearChannelHistoryConfirm", + "chat_clearContactHistoryConfirm", "factoryResetSentTitle", "factoryResetSentBody", "factoryResetSentBleBody", From 25fa71c21239fcc6a150b3a1ce3f78ed8a951c95 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:10:04 -0500 Subject: [PATCH 6/7] fix(#1163): review fixes for the misfile epic From the adversarial review of this branch: - A disconnect while a write waited on its re-read left the wait to its 30 s guard. Every disconnect passes _resetSyncProgressState, which now ends that wait at once. - The per-radio history delete snapshots what is stored before deleting, as #1128 does, and empties the screen first, so a message arriving mid-delete survives on screen and on disk. - The copy cleanup also holds aside the frozen pre-row blob of a key it leaves with no rows. Otherwise the load falls back to that blob and the copies come straight back. - A Resync that fails to start is logged instead of dropped. Co-Authored-By: Claude Opus 5.5 --- lib/connector/meshcore_connector.dart | 17 +++++++++---- lib/helpers/channel_slot_ui.dart | 10 +++++++- lib/storage/cross_radio_copy_cleanup.dart | 14 +++++++++++ lib/storage/radio_data_wipe.dart | 16 +++++++++---- test/connector/channel_write_reread_test.dart | 16 +++++++++++++ .../cross_radio_copy_cleanup_test.dart | 24 +++++++++++++++++++ 6 files changed, 87 insertions(+), 10 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 8cd9824a..7f0ed529 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -4865,6 +4865,11 @@ class MeshCoreConnector extends ChangeNotifier { _queueSyncTimeout = null; _queueSyncRetries = 0; _isSyncingChannels = false; + // A write waiting on its re-read must hear now that the re-read will not + // finish, not after its 30 s guard. Every disconnect passes here (#1163). + final syncDone = _channelSyncDone; + _channelSyncDone = null; + if (syncDone != null && !syncDone.isCompleted) syncDone.complete(false); _channelSyncInFlight = false; _channelSyncTimeout?.cancel(); _channelSyncTimeout = null; @@ -12751,6 +12756,14 @@ class MeshCoreConnector extends ChangeNotifier { if (!isConnected || prefix.isEmpty) { return HistoryWipeRefusal.notConnected; } + // Emptied first: a message arriving during the wipe then lands in a fresh + // window, and the wipe's snapshot leaves its stored copy alone, so it + // stays both on screen and on disk. + _channelMessages.clear(); + _windowPskHex.clear(); + _conversations.clear(); + _loadedConversationKeys.clear(); + notifyListeners(); final int removed; try { removed = await wipeRadioMessageHistory(prefix); @@ -12761,10 +12774,6 @@ class MeshCoreConnector extends ChangeNotifier { ); return HistoryWipeRefusal.failed; } - _channelMessages.clear(); - _windowPskHex.clear(); - _conversations.clear(); - _loadedConversationKeys.clear(); for (final channel in List.of(_channels)) { markChannelRead(channel.index); } diff --git a/lib/helpers/channel_slot_ui.dart b/lib/helpers/channel_slot_ui.dart index 7e28e4ce..7c3c4a95 100644 --- a/lib/helpers/channel_slot_ui.dart +++ b/lib/helpers/channel_slot_ui.dart @@ -7,6 +7,7 @@ import 'package:provider/provider.dart'; import '../connector/meshcore_connector.dart'; import '../l10n/l10n.dart'; import '../models/channel.dart'; +import '../utils/app_logger.dart'; import 'channel_slot_decision.dart'; import 'snack_bar_builder.dart'; @@ -129,7 +130,14 @@ void resyncChannels(BuildContext context, MeshCoreConnector connector) { } return; } - unawaited(connector.getChannels(force: true)); + unawaited( + connector.getChannels(force: true).catchError((Object e) { + appLogger.error( + 'Resync channels failed to start: $e', + tag: 'ChannelSync', + ); + }), + ); } /// Asks what a key change does with [channelName]'s message history: kept diff --git a/lib/storage/cross_radio_copy_cleanup.dart b/lib/storage/cross_radio_copy_cleanup.dart index 99f88549..4c866880 100644 --- a/lib/storage/cross_radio_copy_cleanup.dart +++ b/lib/storage/cross_radio_copy_cleanup.dart @@ -151,12 +151,25 @@ class CrossRadioCopyCleanup { for (final r in decision.copies) { byKey.putIfAbsent(r.storeKey, () => []).add(r.mergeKey); } + var blobsHeld = 0; for (final entry in byKey.entries) { await blobs.moveMessageRows( entry.key, '$heldPrefix${entry.key}', entry.value, ); + // A key left with no rows reads its frozen pre-#920 blob instead, + // which would put the copies straight back on screen. Rows are a + // superset of that blob (the #952 gate), so when every row was a copy + // the blob holds only copies: it is held aside too (review of #1163). + if (await blobs.messageRowCount(entry.key) == 0) { + final blob = await blobs.read(entry.key); + if (blob != null) { + await blobs.write('$heldPrefix${entry.key}', blob); + await blobs.deleteEverywhere(entry.key); + blobsHeld++; + } + } } await blobs.write( doneMarkerKey, @@ -164,6 +177,7 @@ class CrossRadioCopyCleanup { 'at': DateTime.now().toIso8601String(), 'held': decision.copies.length, 'undecided': decision.undecided, + 'blobsHeld': blobsHeld, 'keys': {for (final e in byKey.entries) e.key: e.value.length}, }), ); diff --git a/lib/storage/radio_data_wipe.dart b/lib/storage/radio_data_wipe.dart index 7dbede05..fbe8d023 100644 --- a/lib/storage/radio_data_wipe.dart +++ b/lib/storage/radio_data_wipe.dart @@ -68,6 +68,14 @@ Future wipeRadioMessageHistory(String radioPrefix) async { final blobs = BlobStore.instance; final prefixes = ['channel_messages_$radioPrefix', 'messages_$radioPrefix']; + // What exists now is what goes. A message saved while this runs is not in + // the snapshot and survives, the #1128 rule (review of #1163). + final rowSnapshot = >{ + for (final storeKey in await blobs.messageStoreKeys()) + if (prefixes.any(storeKey.startsWith)) + storeKey: await blobs.messageMergeKeys(storeKey), + }; + var removed = 0; for (final prefix in prefixes) { for (final key in await blobs.keysWithPrefix(prefix)) { @@ -75,11 +83,9 @@ Future wipeRadioMessageHistory(String radioPrefix) async { removed++; } } - for (final storeKey in await blobs.messageStoreKeys()) { - if (prefixes.any(storeKey.startsWith)) { - await blobs.deleteMessageRows(storeKey); - removed++; - } + for (final entry in rowSnapshot.entries) { + await blobs.deleteMessageRowsIn(entry.key, entry.value); + removed++; } return removed; } diff --git a/test/connector/channel_write_reread_test.dart b/test/connector/channel_write_reread_test.dart index 48791851..4cc4f3aa 100644 --- a/test/connector/channel_write_reread_test.dart +++ b/test/connector/channel_write_reread_test.dart @@ -73,6 +73,22 @@ void main() { }); }); + test('a disconnect during the re-read ends the wait at once', () async { + // The radio goes quiet: no reply to the write, none to the re-read. + c.sendFrameOverrideForTest = (_) {}; + final write = c.setChannel(3, 'Weather', _psk(0x22)); + await Future.delayed(const Duration(milliseconds: 60)); + expect(c.isSyncingChannels, isTrue, reason: 'the re-read is running'); + + await c.disconnect(manual: true); + + expect( + await write.timeout(const Duration(seconds: 5)), + ChannelWrite.noReply, + reason: 'before the fix this waited out the 30 s guard', + ); + }); + group('a delete with no reply', () { test('is reported done when the re-read shows the slot empty', () async { final result = await c.deleteChannel(3); diff --git a/test/storage/cross_radio_copy_cleanup_test.dart b/test/storage/cross_radio_copy_cleanup_test.dart index 195fc21d..2141c2f2 100644 --- a/test/storage/cross_radio_copy_cleanup_test.dart +++ b/test/storage/cross_radio_copy_cleanup_test.dart @@ -145,6 +145,30 @@ void main() { }, ); + test('a key left with no rows has its old blob held aside too, so the ' + 'copies cannot come back from it', () async { + await seedFieldPattern(); + // B's offband history from before rows (#920): the same copy, frozen. + await blobs.write( + _key(_b, 'offband'), + jsonEncode([ + {'text': 'alert', 'rxTime': _t0 + _min}, + ]), + ); + + await CrossRadioCopyCleanup.run(blobs); + + expect(await blobs.read(_key(_b, 'offband')), isNull); + expect( + await blobs.read( + '${CrossRadioCopyCleanup.heldPrefix}${_key(_b, 'offband')}', + ), + isNotNull, + reason: 'held, not deleted', + ); + expect(await blobs.messageMergeKeys(_key(_a, 'claude')), {'alert'}); + }); + test( 'runs once: a later launch does not touch the history again', () async { From c628491062d3cd7c6ab150574e1fbb50e36506c3 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:14:08 -0500 Subject: [PATCH 7/7] fix(#1163): name a failed Resync accurately in the log Co-Authored-By: Claude Opus 5.5 --- lib/helpers/channel_slot_ui.dart | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/helpers/channel_slot_ui.dart b/lib/helpers/channel_slot_ui.dart index 7c3c4a95..a4d0a8e2 100644 --- a/lib/helpers/channel_slot_ui.dart +++ b/lib/helpers/channel_slot_ui.dart @@ -132,10 +132,7 @@ void resyncChannels(BuildContext context, MeshCoreConnector connector) { } unawaited( connector.getChannels(force: true).catchError((Object e) { - appLogger.error( - 'Resync channels failed to start: $e', - tag: 'ChannelSync', - ); + appLogger.error('Resync channels failed: $e', tag: 'ChannelSync'); }), ); }