From afbacbc7ebe9a3373fe2e2b6afee6a9a4ca2e949 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:34:26 -0500 Subject: [PATCH 1/6] fix(#1062): fail-closed channel sync, ingress barrier, slot identity diff Epic A of #1061, fixing the #1060 class: the client's slot-to-channel map could silently diverge from the device and misroute notifications and conversations. - A slot the device never answers for is UNKNOWN: tracked, surfaced via a persistent channels-screen banner with Retry, and never backfilled from the previous list. Lookups for it fail closed, including notification evaluation, which now suppresses instead of defaulting to noisy. - Ingress barrier: live channel traffic holds until this connection's list is confirmed, then flushes. Pull-based message frames are never dropped (the radio already popped them); lossy raw sniffs stay bounded. Raw-RX no longer matches the offline cache. - Per-slot unread counts survive a sync only when the slot keeps the same PSK; identity changes are listed in a dismissible notice and logged. - A sync with unconfirmed slots does not overwrite the last fully-confirmed offline cache; a sync that fails on a live connection retries itself. New strings English-only per the #1021-era ruling; regenerated l10n + untranslated.json committed. Co-Authored-By: Claude Fable 5 --- lib/connector/meshcore_connector.dart | 257 +++++++++++++++++--- lib/l10n/app_en.arb | 18 ++ lib/l10n/app_localizations.dart | 24 ++ lib/l10n/app_localizations_bg.dart | 16 ++ lib/l10n/app_localizations_de.dart | 16 ++ lib/l10n/app_localizations_en.dart | 16 ++ lib/l10n/app_localizations_es.dart | 16 ++ lib/l10n/app_localizations_fr.dart | 16 ++ lib/l10n/app_localizations_hu.dart | 16 ++ lib/l10n/app_localizations_it.dart | 16 ++ lib/l10n/app_localizations_ja.dart | 16 ++ lib/l10n/app_localizations_ko.dart | 16 ++ lib/l10n/app_localizations_nl.dart | 16 ++ lib/l10n/app_localizations_pl.dart | 16 ++ lib/l10n/app_localizations_pt.dart | 16 ++ lib/l10n/app_localizations_ru.dart | 16 ++ lib/l10n/app_localizations_sk.dart | 16 ++ lib/l10n/app_localizations_sl.dart | 16 ++ lib/l10n/app_localizations_sv.dart | 16 ++ lib/l10n/app_localizations_uk.dart | 16 ++ lib/l10n/app_localizations_zh.dart | 16 ++ lib/screens/channels_screen.dart | 35 +++ test/connector/channel_sync_truth_test.dart | 203 ++++++++++++++++ untranslated.json | 68 ++++++ 24 files changed, 857 insertions(+), 36 deletions(-) create mode 100644 test/connector/channel_sync_truth_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 454f00a6..0341a480 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -579,6 +579,38 @@ class MeshCoreConnector extends ChangeNotifier { int _totalChannelsToRequest = 0; List _previousChannelsCache = []; static const int _maxChannelSyncRetries = 3; + + // #1062: fail-closed channel sync. A slot the device never answered for is + // UNKNOWN: tracked here, surfaced to the UI, and never backfilled from a + // previous list (that backfill is how a stale slot map misrouted + // notifications and conversations, #1060). + final Set _unconfirmedChannelSlots = {}; + + /// Device slots this connection's sync could not confirm. Non-empty means + /// the channel list has holes the UI must surface (#1062). + Set get unconfirmedChannelSlots => + Set.unmodifiable(_unconfirmedChannelSlots); + + // #1062: ingress barrier. Live channel traffic is held while this + // connection's channel list is not yet synced, then flushed, so a message + // is never filed against a guessed slot map. + bool _channelListSynced = false; + final List _heldChannelMsgFrames = []; + final List _heldRawChannelFrames = []; + static const int _maxHeldChannelFrames = 64; + + /// Human-readable per-slot identity changes found by the latest completed + /// sync (old name -> new name). Surfaced once by the channels screen (#1062). + final List _slotIdentityChanges = []; + List get slotIdentityChanges => + List.unmodifiable(_slotIdentityChanges); + + /// User dismissed the slot-identity-change notice (#1062). + void acknowledgeSlotIdentityChanges() { + _slotIdentityChanges.clear(); + notifyListeners(); + } + static const int _channelSyncTimeoutMs = 2000; // 2 second timeout per channel static const Duration _batteryPollInterval = Duration(seconds: 120); @@ -4039,6 +4071,20 @@ class MeshCoreConnector extends ChangeNotifier { @visibleForTesting void setConnectedForTest() => _state = MeshCoreConnectionState.connected; + // #1062 test hooks: drive the sync timeout path without real timers, seed + // the offline cache, and observe the fail-closed slot lookup. + @visibleForTesting + void handleChannelSyncTimeoutForTest(int channelIndex) => + _handleChannelSyncTimeout(channelIndex); + + @visibleForTesting + void seedCachedChannelsForTest(List channels) { + _cachedChannels = List.from(channels); + } + + @visibleForTesting + Channel? findChannelByIndexForTest(int index) => _findChannelByIndex(index); + @visibleForTesting void setAppDebugLogServiceForTest(AppDebugLogService service) => _appDebugLogService = service; @@ -4126,6 +4172,14 @@ class MeshCoreConnector extends ChangeNotifier { _nextChannelIndexToRequest = 0; _totalChannelsToRequest = 0; _previousChannelsCache.clear(); + // #1062: a new connection starts with an unconfirmed list. Held MESSAGE + // frames are kept: the radio already popped them from its queue, so they + // exist nowhere else, and the next confirmed sync files them. Raw sniff + // frames are lossy observations; a dead connection's are stale. + _channelListSynced = false; + _unconfirmedChannelSlots.clear(); + _slotIdentityChanges.clear(); + _heldRawChannelFrames.clear(); } bool get _shouldAutoReconnect => @@ -6233,6 +6287,11 @@ class MeshCoreConnector extends ChangeNotifier { _isLoadingChannels = true; _isSyncingChannels = true; _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 + // against a stale one (#1062). + _channelListSynced = false; + _unconfirmedChannelSlots.clear(); _previousChannelsCache = List.from(_channels); _channels.clear(); _nextChannelIndexToRequest = 0; @@ -6254,6 +6313,11 @@ class MeshCoreConnector extends ChangeNotifier { return; } + // Queued continuations from retries can land after the sync already + // finished; without this guard they re-enter _completeChannelSync against + // the reset counters (#1062). + if (!_isSyncingChannels) return; + if (_channelSyncInFlight) return; // Check if we've requested all channels @@ -6298,26 +6362,18 @@ class MeshCoreConnector extends ChangeNotifier { _channelSyncInFlight = false; unawaited(_requestNextChannel()); } else { - // Max retries reached for this channel, restore from cache and move to next - debugPrint( - '[ChannelSync] Max retries reached for channel $channelIndex, attempting cache restore', + // Max retries reached: the slot's contents are UNKNOWN. It used to be + // restored from the previous list here, which silently pinned a + // pre-reconfiguration channel at this index and misrouted notifications + // and conversations (#1060). Fail closed instead: leave the slot empty, + // record it, surface it (#1062). + _unconfirmedChannelSlots.add(channelIndex); + _appDebugLogService?.error( + 'Channel sync: device never answered for slot $channelIndex; ' + 'slot left unknown, not restored from cache', + tag: 'ChannelSync', ); - // Try to restore this channel from cache - try { - final cachedChannel = _previousChannelsCache.firstWhere( - (c) => c.index == channelIndex, - ); - if (!cachedChannel.isEmpty) { - _channels.add(cachedChannel); - debugPrint( - '[ChannelSync] Restored channel $channelIndex (${cachedChannel.name}) from cache', - ); - } - } catch (e) { - // No cached channel found, that's okay - } - // Move to next channel _nextChannelIndexToRequest++; _channelSyncRetries = 0; @@ -6331,25 +6387,66 @@ class MeshCoreConnector extends ChangeNotifier { _channelSyncTimeout?.cancel(); debugPrint( - '[ChannelSync] Sync complete: received ${_channels.length}/$_totalChannelsToRequest channels', + '[ChannelSync] Sync complete: received ${_channels.length}/$_totalChannelsToRequest channels' + '${_unconfirmedChannelSlots.isEmpty ? '' : ', unconfirmed slots: $_unconfirmedChannelSlots'}', ); _cleanupChannelSync(completed: true); - // Cache channels for offline use - _cachedChannels = List.from(_channels); - unawaited( - _channelStore.saveChannels(_channels).catchError((Object e) { - _appDebugLogService?.error( - 'Failed to persist channels (channel sync): $e', - tag: 'ChannelStore', + // #1062: per-slot identity diff against the last persisted truth. A slot + // whose PSK changed got a different channel; say so once instead of + // letting per-slot state ride across identities. + _slotIdentityChanges.clear(); + for (final fresh in _channels) { + final prior = _cachedChannels.cast().firstWhere( + (c) => c?.index == fresh.index, + orElse: () => null, + ); + if (prior != null && + !prior.isEmpty && + !fresh.isEmpty && + prior.pskHex != fresh.pskHex) { + _slotIdentityChanges.add( + 'slot ${fresh.index}: ${prior.name} -> ${fresh.name}', ); - }), - ); + _appDebugLogService?.warn( + 'Channel slot ${fresh.index} changed identity on the radio: ' + '"${prior.name}" -> "${fresh.name}"', + tag: 'ChannelSync', + ); + } + } + + if (_unconfirmedChannelSlots.isEmpty) { + // Full confirmation: the fresh list is the truth, replace the cache. + _cachedChannels = List.from(_channels); + unawaited( + _channelStore.saveChannels(_channels).catchError((Object e) { + _appDebugLogService?.error( + 'Failed to persist channels (channel sync): $e', + tag: 'ChannelStore', + ); + }), + ); + } else { + // Holes: keep the last fully-confirmed persisted list for offline use + // rather than overwriting it with a partial one. The holes are surfaced + // via [unconfirmedChannelSlots] and lookups for those slots fail closed. + _appDebugLogService?.error( + 'Channel sync finished with unconfirmed slots ' + '$_unconfirmedChannelSlots; cached list NOT overwritten. ' + 'Retry the sync to confirm them.', + tag: 'ChannelSync', + ); + } _recalculateCachedChannelsUnreadTotal(); // Apply ordering and notify UI _applyChannelOrder(); + + // #1062: open the ingress barrier and file what arrived mid-sync. + _channelListSynced = true; + _flushHeldChannelFrames(); notifyListeners(); // #839: one-time migration of the pre-per-radio notify state into THIS @@ -6380,6 +6477,50 @@ class MeshCoreConnector extends ChangeNotifier { ); } + /// Replays channel traffic held while the list was unconfirmed (#1062). + /// Runs after [_channelListSynced] flips true, so the handlers file against + /// the fresh list; a frame whose slot is still unconfirmed re-holds. + void _flushHeldChannelFrames() { + if (_heldChannelMsgFrames.isEmpty && _heldRawChannelFrames.isEmpty) return; + final msgFrames = List.from(_heldChannelMsgFrames); + final rawFrames = List.from(_heldRawChannelFrames); + _heldChannelMsgFrames.clear(); + _heldRawChannelFrames.clear(); + _appDebugLogService?.info( + 'Channel list synced; filing ${msgFrames.length} held message frame(s) ' + 'and ${rawFrames.length} held raw frame(s)', + tag: 'ChannelSync', + ); + for (final f in msgFrames) { + _handleIncomingChannelMessage(f); + } + for (final f in rawFrames) { + _handleLogRxData(f); + } + } + + /// Holds a frame behind the ingress barrier. Message frames are pull-based + /// replies the radio has already popped from its queue, so they are NEVER + /// dropped (the hold only lives for the seconds a sync takes). Raw sniff + /// frames are lossy by nature and stay bounded: overflow drops the oldest + /// and says so loudly (#1062). + void _holdChannelFrame( + List queue, + Uint8List frame, + String kind, { + required bool bounded, + }) { + if (bounded && queue.length >= _maxHeldChannelFrames) { + queue.removeAt(0); + _appDebugLogService?.error( + 'Held-$kind queue overflow while the channel list is unconfirmed; ' + 'dropped the oldest held frame', + tag: 'ChannelSync', + ); + } + queue.add(Uint8List.fromList(frame)); + } + void _cleanupChannelSync({required bool completed}) { _isSyncingChannels = false; _channelSyncInFlight = false; @@ -6406,6 +6547,16 @@ class MeshCoreConnector extends ChangeNotifier { // Keep cache on failure/disconnection for future attempts if (!completed) { + // #1062: a failed sync on a live connection leaves the ingress barrier + // closed with nothing scheduled to open it; retry rather than letting + // held messages starve. (A dead connection re-syncs on reconnect.) + if (isConnected) { + _channelsChangedDebounce?.cancel(); + _channelsChangedDebounce = Timer( + const Duration(seconds: 3), + () => unawaited(getChannels(force: true)), + ); + } notifyListeners(); } } @@ -9229,9 +9380,21 @@ class MeshCoreConnector extends ChangeNotifier { // Per-channel notification level, keyed by the channel's PSK identity so // the setting survives a rename and does not follow a reused slot (#259). // Evaluated against resolvedText so a translated mention still matches. + // #1062: an unknown slot means an unknown PSK means an unknowable mode; + // fail closed (no notification) rather than defaulting to noisy. + final slotChannel = _findChannelByIndex(channelIndex); + if (slotChannel == null && + _unconfirmedChannelSlots.contains(channelIndex)) { + _appDebugLogService?.warn( + 'Suppressing notification for channel slot $channelIndex: slot is ' + 'unconfirmed, its notify mode cannot be resolved', + tag: 'ChannelSync', + ); + return; + } final mode = _appSettingsService!.channelNotifyMode( devicePrefix: selfPublicKeyHex, - pskHex: _findChannelByIndex(channelIndex)?.pskHex, + pskHex: slotChannel?.pskHex, ); switch (mode) { case ChannelNotifyMode.off: @@ -9266,6 +9429,17 @@ class MeshCoreConnector extends ChangeNotifier { if (_isSyncingQueuedMessages) { _handleQueuedMessageReceived(); } + // #1062 ingress barrier: never file a message against a channel list that + // this connection has not confirmed; hold it and flush post-sync. + if (isConnected && !_channelListSynced) { + _holdChannelFrame( + _heldChannelMsgFrames, + frame, + 'message', + bounded: false, + ); + return; + } final parsed = ChannelMessage.fromFrame(frame); if (parsed != null && parsed.channelIndex != null) { // Device-composed (outgoing) messages legitimately carry our own name and @@ -9338,11 +9512,16 @@ class MeshCoreConnector extends ChangeNotifier { final channelHash = payload.readByte(); final encrypted = Uint8List.fromList(payload.readRemainingBytes()); - // Use cached channels as fallback if live channels not yet loaded - final channelsToSearch = _channels.isNotEmpty - ? _channels - : _cachedChannels; - for (final channel in channelsToSearch) { + // #1062 ingress barrier: a raw frame is filed by matching its channel + // hash against the CLIENT's list and reusing that object's index, so a + // stale or mid-sync list files it into the wrong conversation. Hold + // until this connection's list is confirmed; never match the offline + // cache (its indexes may describe a layout the radio no longer has). + if (!_channelListSynced) { + _holdChannelFrame(_heldRawChannelFrames, frame, 'raw', bounded: true); + return; + } + for (final channel in _channels) { if (channel.isEmpty) continue; final hash = _computeChannelHash(channel.psk); if (hash != channelHash) continue; @@ -9645,12 +9824,14 @@ class MeshCoreConnector extends ChangeNotifier { '[ChannelSync] Received channel ${channel.index}: ${channel.isEmpty ? "empty" : channel.name}', ); - // Preserve unread count from cached channel + // Preserve unread count from the cached channel, but only when the slot + // still holds the SAME channel. An unread count following the slot across + // an identity change is another channel's count (#1062). final cachedChannel = _cachedChannels.cast().firstWhere( (c) => c?.index == channel.index, orElse: () => null, ); - if (cachedChannel != null) { + if (cachedChannel != null && cachedChannel.pskHex == channel.pskHex) { channel.unreadCount = cachedChannel.unreadCount; } @@ -9750,6 +9931,10 @@ class MeshCoreConnector extends ChangeNotifier { } Channel? _findChannelByIndex(int index) { + // #1062: an unconfirmed slot's contents are unknown. Returning the cached + // occupant here is how a stale identity (wrong PSK, wrong name) attached + // itself to live traffic; fail closed instead. + if (_unconfirmedChannelSlots.contains(index)) return null; return _channels.cast().firstWhere( (c) => c?.index == index, orElse: () => null, diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 8960c537..317b1ee5 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -836,6 +836,24 @@ "channels_noChannelsConfigured": "No channels configured", "channels_addPublicChannel": "Add Public Channel", "channels_searchChannels": "Search channels...", + "channels_unconfirmedSlots": "The radio did not confirm channel slot(s) {slots}. Those channels are unknown until a sync succeeds.", + "@channels_unconfirmedSlots": { + "placeholders": { + "slots": { + "type": "String" + } + } + }, + "channels_retrySync": "Retry sync", + "channels_slotIdentityChanged": "Channel layout changed on the radio: {changes}", + "@channels_slotIdentityChanged": { + "placeholders": { + "changes": { + "type": "String" + } + } + }, + "common_dismiss": "Dismiss", "channels_noChannelsFound": "No channels found", "channels_channelIndex": "Channel {index}", "@channels_channelIndex": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index c8b31e00..3044aeca 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2818,6 +2818,30 @@ abstract class AppLocalizations { /// **'Search channels...'** String get channels_searchChannels; + /// No description provided for @channels_unconfirmedSlots. + /// + /// In en, this message translates to: + /// **'The radio did not confirm channel slot(s) {slots}. Those channels are unknown until a sync succeeds.'** + String channels_unconfirmedSlots(String slots); + + /// No description provided for @channels_retrySync. + /// + /// In en, this message translates to: + /// **'Retry sync'** + String get channels_retrySync; + + /// No description provided for @channels_slotIdentityChanged. + /// + /// In en, this message translates to: + /// **'Channel layout changed on the radio: {changes}'** + String channels_slotIdentityChanged(String changes); + + /// No description provided for @common_dismiss. + /// + /// In en, this message translates to: + /// **'Dismiss'** + String get common_dismiss; + /// No description provided for @channels_noChannelsFound. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 4aef2fb4..b1b6f5ae 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1579,6 +1579,22 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channels_searchChannels => 'Търсене на канали...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Няма намерени канали'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 2b8d59ac..77afe12f 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1573,6 +1573,22 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_searchChannels => 'Suche Kanäle...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Keine Kanäle gefunden'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 05136266..39478abc 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1555,6 +1555,22 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_searchChannels => 'Search channels...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'No channels found'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index be9d4a3e..2183176d 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1574,6 +1574,22 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_searchChannels => 'Buscar canales...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'No se encontraron canales'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 6738f5f9..7f729f47 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1579,6 +1579,22 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_searchChannels => 'Rechercher des canaux...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Aucun canal trouvé'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index e5bd2129..a6c3b9a4 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1580,6 +1580,22 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_searchChannels => 'Keresési opciók...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Nincs megtalálható csatorna'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index b1978d2b..5b4b9d0f 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1575,6 +1575,22 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_searchChannels => 'Cerca canali...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Nessun canale trovato'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index c5638629..74a35229 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1523,6 +1523,22 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_searchChannels => '検索オプション...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'チャンネルが見つかりませんでした'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index eef52521..cc8b2ad4 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1518,6 +1518,22 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_searchChannels => '검색 채널...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => '채널을 찾을 수 없습니다.'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index b3f00605..9a206eed 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1566,6 +1566,22 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_searchChannels => 'Zoek kanalen...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Geen kanalen gevonden'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index b1962d3b..846c6b3f 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1585,6 +1585,22 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_searchChannels => 'Wyszukaj kanały...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Brak znalezionych kanałów'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index b3b57b10..111aecc5 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1575,6 +1575,22 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_searchChannels => 'Pesquisar canais...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Nenhum canal encontrado'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 6748532e..d2724854 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1576,6 +1576,22 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_searchChannels => 'Поиск каналов...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Каналы не найдены'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0d7e01ce..de469971 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1566,6 +1566,22 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_searchChannels => 'Vyhľadávajte kanály...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Neobsiahlo sa žiadnych kanálov.'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index e90ee0f6..77cfd12c 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1563,6 +1563,22 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_searchChannels => 'Poišči kanale...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Ne najdem kanalov.'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index f395a517..b8fec2a9 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1557,6 +1557,22 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_searchChannels => 'Sök kanaler...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Inga kanaler hittades'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index c9ec29de..b1728c8f 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1571,6 +1571,22 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_searchChannels => 'Пошук каналів...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => 'Каналів не знайдено'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index a397f517..64f10bc4 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1504,6 +1504,22 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_searchChannels => '搜索频道...'; + @override + String channels_unconfirmedSlots(String slots) { + return 'The radio did not confirm channel slot(s) $slots. Those channels are unknown until a sync succeeds.'; + } + + @override + String get channels_retrySync => 'Retry sync'; + + @override + String channels_slotIdentityChanged(String changes) { + return 'Channel layout changed on the radio: $changes'; + } + + @override + String get common_dismiss => 'Dismiss'; + @override String get channels_noChannelsFound => '未找到任何频道'; diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 1b2ec301..167a14ea 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -187,6 +187,41 @@ class _ChannelsScreenState extends State return Column( children: [ + // #1062: persistent, undismissable while true. A slot the + // radio never confirmed means its channel is unknown; a + // 4-second toast is not an error surface (SAFELANE 6). + if (connector.unconfirmedChannelSlots.isNotEmpty) + MaterialBanner( + backgroundColor: Theme.of( + context, + ).colorScheme.errorContainer, + content: Text( + context.l10n.channels_unconfirmedSlots( + connector.unconfirmedChannelSlots.toList().join(', '), + ), + ), + actions: [ + TextButton( + onPressed: () => + unawaited(connector.getChannels(force: true)), + child: Text(context.l10n.channels_retrySync), + ), + ], + ), + if (connector.slotIdentityChanges.isNotEmpty) + MaterialBanner( + content: Text( + context.l10n.channels_slotIdentityChanged( + connector.slotIdentityChanges.join('; '), + ), + ), + actions: [ + TextButton( + onPressed: connector.acknowledgeSlotIdentityChanges, + child: Text(context.l10n.common_dismiss), + ), + ], + ), Padding( padding: const EdgeInsets.all(8.0), child: TextField( diff --git a/test/connector/channel_sync_truth_test.dart b/test/connector/channel_sync_truth_test.dart new file mode 100644 index 00000000..83371cee --- /dev/null +++ b/test/connector/channel_sync_truth_test.dart @@ -0,0 +1,203 @@ +// #1062 (Epic A of #1061, fixing #1060): the channel sync is fail-closed and +// atomic, live filing waits behind an ingress barrier, and per-slot state +// never follows a slot across an identity change. +// +// The #1060 field case: a wipe + config re-import rearranged the device's +// channel slots; the old sync backfilled unanswered slots from the previous +// list, so notifications fired for the wrong channel and messages rendered +// inside the wrong conversation. + +import 'dart:typed_data'; + +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/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List _channelInfoFrame({ + required int index, + required String name, + required int pskSeed, +}) { + final frame = Uint8List(50); + frame[0] = respCodeChannelInfo; + frame[1] = index; + final nameBytes = name.codeUnits; + for (var i = 0; i < nameBytes.length && i < 31; i++) { + frame[2 + i] = nameBytes[i]; + } + for (var i = 0; i < 16; i++) { + frame[34 + i] = (pskSeed + i) & 0xFF; + } + return frame; +} + +Uint8List _v3ChannelMsgFrame({required int channelIdx, String text = 'A: hi'}) { + return Uint8List.fromList([ + respCodeChannelMsgRecvV3, + 0, 0, 0, + channelIdx, + 1, // path_len: 1 hop, width 1 + txtTypePlain, + 0x40, 0xE2, 0x01, 0x00, + ...text.codeUnits, + ]); +} + +Channel _channel(int index, String name, int pskSeed) { + final psk = Uint8List.fromList( + List.generate(16, (i) => (pskSeed + i) & 0xFF), + ); + return Channel(index: index, name: name, psk: psk); +} + +MeshCoreConnector _connector() { + final c = MeshCoreConnector(); + c.sendFrameOverrideForTest = (_) {}; + c.setConnectedForTest(); + c.setSelfPublicKeyForTest( + Uint8List.fromList(List.generate(32, (i) => i)), + ); + return c; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + test( + 'an unanswered slot stays UNKNOWN, never backfilled from cache (#1060)', + () async { + final c = _connector(); + c.seedCachedChannelsForTest([_channel(1, 'StaleOccupant', 70)]); + + await c.getChannels(maxChannels: 2); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Fresh0', pskSeed: 10), + ); + // Slot 1 never answers: exhaust the retries. + for (var i = 0; i <= 3; i++) { + c.handleChannelSyncTimeoutForTest(1); + await Future.delayed(Duration.zero); + } + + expect(c.unconfirmedChannelSlots, {1}); + expect(c.channels.map((ch) => ch.name), ['Fresh0']); + expect( + c.channels.any((ch) => ch.name == 'StaleOccupant'), + isFalse, + reason: 'the stale cache occupant must not be restored into the slot', + ); + expect( + c.findChannelByIndexForTest(1), + isNull, + reason: 'lookups for an unconfirmed slot fail closed', + ); + }, + ); + + test( + 'messages arriving mid-sync are held, then filed after the sync', + () async { + final c = _connector(); + + await c.getChannels(maxChannels: 2); + // Barrier is up: a pushed message must not file yet. + c.handleFrameForTest(_v3ChannelMsgFrame(channelIdx: 0)); + expect(c.channelMessagesForTest[0], isNull); + + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Alpha', pskSeed: 10), + ); + await Future.delayed(Duration.zero); + c.handleFrameForTest( + _channelInfoFrame(index: 1, name: 'Beta', pskSeed: 30), + ); + await Future.delayed(Duration.zero); + + expect(c.unconfirmedChannelSlots, isEmpty); + expect( + c.channelMessagesForTest[0], + isNotNull, + reason: 'the held frame files once the list is confirmed', + ); + expect(c.channelMessagesForTest[0]!.single.text, 'hi'); + }, + ); + + test( + 'unread count does not follow a slot across an identity change', + () async { + final c = _connector(); + final stale = _channel(0, 'OldChannel', 70)..unreadCount = 5; + c.seedCachedChannelsForTest([stale]); + + await c.getChannels(maxChannels: 1); + // Same slot, different PSK: a different channel lives here now. + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'NewChannel', pskSeed: 10), + ); + await Future.delayed(Duration.zero); + + expect(c.channels.single.name, 'NewChannel'); + expect( + c.channels.single.unreadCount, + 0, + reason: 'another identity\'s unread count must not ride the slot', + ); + expect(c.slotIdentityChanges, isNotEmpty); + }, + ); + + test( + 'unread count IS preserved when the slot keeps the same channel', + () async { + final c = _connector(); + final same = _channel(0, 'Keep', 10)..unreadCount = 7; + c.seedCachedChannelsForTest([same]); + + await c.getChannels(maxChannels: 1); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Keep', pskSeed: 10), + ); + await Future.delayed(Duration.zero); + + expect(c.channels.single.unreadCount, 7); + expect(c.slotIdentityChanges, isEmpty); + }, + ); + + test( + 'a sync with unconfirmed slots does not overwrite the offline cache', + () async { + final c = _connector(); + c.seedCachedChannelsForTest([ + _channel(0, 'GoodCache0', 10), + _channel(1, 'GoodCache1', 30), + ]); + + await c.getChannels(maxChannels: 2); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Fresh0', pskSeed: 10), + ); + for (var i = 0; i <= 3; i++) { + c.handleChannelSyncTimeoutForTest(1); + await Future.delayed(Duration.zero); + } + + expect(c.unconfirmedChannelSlots, {1}); + // The confirmed slot is live; the unconfirmed one is a hole, and the last + // fully-confirmed cache survives for the next attempt (slot 0 lookup still + // resolves, slot 1 fails closed). + expect(c.findChannelByIndexForTest(0)?.name, 'Fresh0'); + expect(c.findChannelByIndexForTest(1), isNull); + }, + ); +} diff --git a/untranslated.json b/untranslated.json index eb4bc5a4..ea2bfb1d 100644 --- a/untranslated.json +++ b/untranslated.json @@ -126,6 +126,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -465,6 +469,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -804,6 +812,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -1143,6 +1155,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -1482,6 +1498,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -1821,6 +1841,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -2160,6 +2184,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -2499,6 +2527,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -2838,6 +2870,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -3177,6 +3213,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -3516,6 +3556,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -3855,6 +3899,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -4194,6 +4242,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -4533,6 +4585,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -4872,6 +4928,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -5211,6 +5271,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -5550,6 +5614,10 @@ "contact_remoteCli", "contact_remoteCliSubtitle", "contact_cliConsole", + "channels_unconfirmedSlots", + "channels_retrySync", + "channels_slotIdentityChanged", + "common_dismiss", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", From 46255f1ef400450da7dcdb7541772d41cbdcc6fb Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:18:35 -0500 Subject: [PATCH 2/6] fix(#1063): keep per-slot message state from crossing channel identities Persisted channel history has been PSK-keyed since #194; the remnants that could still cross-wire on a slot reassignment were in-memory and legacy. Epic B of #1061, stacked on #1062: - _completeChannelSync's identity diff now drops the slot's in-memory conversation and reloads it from the store, which reads the NEW identity's own history through the (now fail-closed) resolver. - setChannel's reassignment clear purges only the LEGACY slot-index keys (new clearLegacySlotHistory), so the outgoing occupant's PSK-keyed history survives and comes back if the channel is re-added. True deletes (deleteChannel) keep the full both-key clear. - A WRITE that falls back to the slot-index key now logs an error with the orphaning consequence spelled out; post-#1062 live ingress cannot reach it. - The #193-era comment claiming history is slot-keyed is corrected and the setChannel/resolver interplay documented. Tests: 2 connector tests (in-memory drop on identity change, kept on same identity) + 5 store tests (legacy purge, PSK history survival, no adoption onto the new occupant, true delete). Issue: #1063 Co-Authored-By: Claude Fable 5 --- lib/connector/meshcore_connector.dart | 25 +++- lib/storage/channel_message_store.dart | 79 ++++++++--- test/connector/channel_sync_truth_test.dart | 61 +++++++++ .../channel_message_store_identity_test.dart | 128 ++++++++++++++++++ 4 files changed, 267 insertions(+), 26 deletions(-) create mode 100644 test/storage/channel_message_store_identity_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 0341a480..7f554189 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -6414,6 +6414,13 @@ class MeshCoreConnector extends ChangeNotifier { '"${prior.name}" -> "${fresh.name}"', tag: 'ChannelSync', ); + // #1063: the in-memory conversation is the one per-slot message store + // left (persisted history is PSK-keyed, #194). Drop the old occupant's + // messages so they cannot render under the new channel, then reload + // 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); + unawaited(_loadChannelMessages(fresh.index)); } } @@ -6574,19 +6581,23 @@ class MeshCoreConnector extends ChangeNotifier { Future setChannel(int index, String name, Uint8List psk) async { if (!isConnected) return; - // Channel history is stored keyed by the reusable slot [index], not by the - // channel's PSK. If this slot is being (re)assigned to a different channel - // than the one whose history is stored here, clear the stale history so a - // previous occupant's messages (e.g. #echo) don't surface under the newly - // added channel. Preserve only when the slot already holds the SAME channel - // (same PSK), e.g. a rename. (#193) + // Persisted channel history is keyed by the channel's PSK identity (#194), + // so reassigning this slot to a different channel cannot surface the old + // occupant's messages THERE. Two slot-keyed remnants still can, and both + // are handled when the slot changes occupant (different PSK): + // - legacy slot-index keys (pre-#194) would be adopted onto the new + // occupant by the store's one-time migration; purge them (#193/#1063). + // - the in-memory conversation map is slot-keyed; drop this slot's entry. + // The old occupant's PSK-keyed history is deliberately left intact: if + // that channel is ever re-added (any slot), its history comes back + // (#1063). A rename (same PSK) keeps everything. final existing = _findChannelByIndex(index); final sameChannel = existing != null && listEquals(existing.psk, psk); await sendFrame(buildSetChannelFrame(index, name, psk)); if (!sameChannel) { - await _channelMessageStore.clearChannelMessages(index); + await _channelMessageStore.clearLegacySlotHistory(index); _channelMessages.remove(index); } diff --git a/lib/storage/channel_message_store.dart b/lib/storage/channel_message_store.dart index 9c5bd445..adc5b5be 100644 --- a/lib/storage/channel_message_store.dart +++ b/lib/storage/channel_message_store.dart @@ -126,23 +126,45 @@ class ChannelMessageStore { /// Active storage key: PSK identity when known, else the slot index. /// - /// The index fallback is legitimate before a channel list has loaded, but it - /// reads a DIFFERENT key: if history was already migrated to the PSK key, the - /// caller gets an empty list that is indistinguishable from data loss. - /// SAFELANE 6 - this must never be silent. Falling back where a resolver - /// exists means the channel list was not ready, which is the #333 race. - String _storageKey(int channelIndex) { + /// The index fallback is legitimate on a READ before a channel list has + /// loaded, but it reads a DIFFERENT key: if history was already migrated to + /// the PSK key, the caller gets an empty list that is indistinguishable from + /// data loss. SAFELANE 6 - this must never be silent. Falling back where a + /// resolver exists means the channel list was not ready, which is the #333 + /// race. + /// + /// A WRITE must never land on the index fallback: the one-time adoption in + /// [loadChannelMessages] only runs while the PSK key is EMPTY, so a message + /// written to the index key of a channel that already has PSK-keyed history + /// is orphaned - stored, never read again. Since #1062 the connector files + /// live traffic only after the channel list is confirmed (ingress barrier + + /// fail-closed slot lookup), so a write-side fallback is a defect; it is + /// logged as an error and [forWrite] marks the call sites that save, remove + /// or clear. (#1063) + String _storageKey(int channelIndex, {bool forWrite = false}) { final pskHex = channelPskResolver?.call(channelIndex); if (pskHex != null && pskHex.isNotEmpty) { return '$keyFor$_pskMarker$pskHex'; } if (channelPskResolver != null) { - appLogger.warn( - 'Channel $channelIndex has no PSK yet; falling back to the slot-index ' - 'key. Any history already migrated to the PSK key will read as EMPTY. ' - 'This means the channel list was not loaded first (#333).', - tag: 'Storage', - ); + if (forWrite) { + appLogger.error( + 'WRITE for channel $channelIndex fell back to the slot-index key: ' + 'the slot did not resolve to a PSK. If this channel already has ' + 'PSK-keyed history, this write is orphaned (adoption only runs on ' + 'an empty PSK key). Post-#1062 ingress cannot reach this; a user ' + 'action on an unconfirmed slot can. (#1063)', + tag: 'Storage', + ); + } else { + appLogger.warn( + 'Channel $channelIndex has no PSK yet; falling back to the ' + 'slot-index key. Any history already migrated to the PSK key will ' + 'read as EMPTY. This means the channel list was not loaded first ' + '(#333).', + tag: 'Storage', + ); + } } return _indexKey(channelIndex); } @@ -165,7 +187,7 @@ class ChannelMessageStore { // the in-memory copy win so edits/reactions/status updates are captured. // Deletion has its own path (removeChannelMessage) so this never // resurrects a message the user deleted. - final key = _storageKey(channelIndex); + final key = _storageKey(channelIndex, forWrite: true); final blobs = BlobStore.instance; // Rows (#920): one upsert per message in the list, which costs the same @@ -230,7 +252,7 @@ class ChannelMessageStore { ChannelMessage message, ) async { if (publicKeyHex.isEmpty) return; - final key = _storageKey(channelIndex); + final key = _storageKey(channelIndex, forWrite: true); final blobs = BlobStore.instance; if (await blobs.ensureMessageRowsMigrated(key, channelHistoryToRows)) { await blobs.deleteMessageRow(key, _mergeKey(message)); @@ -351,19 +373,38 @@ class ChannelMessageStore { return out; } - /// Clear messages for a specific channel slot. Removes BOTH the PSK-identity - /// key and the raw slot-index key: deleteChannel needs the channel's own - /// history gone, and setChannel's reuse-clear (#193) needs any stale - /// slot-index history gone so it can't be migrated onto the new occupant. + /// Clear a channel's history outright: BOTH the PSK-identity key and the + /// raw slot-index key. This is the true-delete path (deleteChannel, the + /// user's explicit clear) - the channel's own history must be gone. + /// Slot reassignment uses [clearLegacySlotHistory] instead, which keeps the + /// outgoing occupant's PSK-keyed history. (#1063) Future clearChannelMessages(int channelIndex) async { final blobs = BlobStore.instance; - for (final key in {_storageKey(channelIndex), _indexKey(channelIndex)}) { + for (final key in { + _storageKey(channelIndex, forWrite: true), + _indexKey(channelIndex), + }) { await blobs.deleteEverywhere(key); // Rows as well, or a clear would leave the history readable (#920). 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, + /// [loadChannelMessages]' one-time adoption would migrate the previous + /// occupant's pre-#194 history onto the new occupant. The previous + /// occupant's PSK-keyed history is NOT touched, so re-adding that channel + /// later restores its messages. (#1063) + Future clearLegacySlotHistory(int channelIndex) async { + final blobs = BlobStore.instance; + for (final key in {_indexKey(channelIndex), '$_keyPrefix$channelIndex'}) { + await blobs.deleteEverywhere(key); + await blobs.deleteMessageRows(key); + } + } + /// Clear all channel messages Future clearAllChannelMessages() async { final blobs = BlobStore.instance; diff --git a/test/connector/channel_sync_truth_test.dart b/test/connector/channel_sync_truth_test.dart index 83371cee..ae37b3b8 100644 --- a/test/connector/channel_sync_truth_test.dart +++ b/test/connector/channel_sync_truth_test.dart @@ -13,6 +13,7 @@ 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/storage/prefs_manager.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -174,6 +175,66 @@ void main() { }, ); + test( + 'in-memory messages do not follow a slot across an identity change (#1063)', + () async { + final c = _connector(); + c.seedCachedChannelsForTest([_channel(0, 'OldChannel', 70)]); + c.channelMessagesForTest[0] = [ + ChannelMessage( + senderName: 'x', + text: 'old occupant message', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000), + isOutgoing: false, + channelIndex: 0, + messageId: 'old1', + ), + ]; + + await c.getChannels(maxChannels: 1); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'NewChannel', pskSeed: 10), + ); + // Settle the sync completion and the unawaited history reload. + await Future.delayed(Duration.zero); + await Future.delayed(Duration.zero); + + expect( + c.channelMessagesForTest[0] ?? const [], + isEmpty, + reason: + "the old occupant's conversation must not render under the new " + 'channel; the slot reloads from the NEW identity\'s (empty) store', + ); + }, + ); + + test( + 'in-memory messages stay when the slot keeps the same channel', + () async { + final c = _connector(); + c.seedCachedChannelsForTest([_channel(0, 'Keep', 10)]); + c.channelMessagesForTest[0] = [ + ChannelMessage( + senderName: 'x', + text: 'kept', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000), + isOutgoing: false, + channelIndex: 0, + messageId: 'k1', + ), + ]; + + await c.getChannels(maxChannels: 1); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Keep', pskSeed: 10), + ); + await Future.delayed(Duration.zero); + + expect(c.channelMessagesForTest[0]!.single.text, 'kept'); + }, + ); + test( 'a sync with unconfirmed slots does not overwrite the offline cache', () async { diff --git a/test/storage/channel_message_store_identity_test.dart b/test/storage/channel_message_store_identity_test.dart new file mode 100644 index 00000000..b2f8e0be --- /dev/null +++ b/test/storage/channel_message_store_identity_test.dart @@ -0,0 +1,128 @@ +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel_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/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #1063 (Epic B of #1061): slot reassignment must not move history between +/// channel identities. Persisted history is PSK-keyed (#194); the remnants a +/// reassignment has to deal with are the LEGACY slot-index keys, and only +/// those - the outgoing occupant's PSK-keyed history survives so re-adding +/// that channel brings its messages back. +void main() { + late OffbandDatabase db; + late BlobStore blobs; + + const pskA = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; + const pskB = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + ChannelMessage chan(int i, {String? text}) => ChannelMessage( + senderName: 's', + text: text ?? 'm$i', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i), + isOutgoing: false, + channelIndex: 0, + messageId: 'id$i', + ); + + ChannelMessageStore store({String? psk}) => ChannelMessageStore() + ..setPublicKeyHex = 'd' * 20 + ..channelPskResolver = (_) => psk; + + test('clearLegacySlotHistory purges the legacy slot keys', () async { + // Pre-#194 remnants: device-scoped index key and the unscoped one. + await blobs.write( + 'channel_messages_dddddddddd0', + ChannelMessageStore.encodeHistoryForTest([chan(1)]), + ); + await blobs.write( + 'channel_messages_0', + ChannelMessageStore.encodeHistoryForTest([chan(2)]), + ); + + await store(psk: pskA).clearLegacySlotHistory(0); + + expect( + await blobs.readWithPrefsFallback('channel_messages_dddddddddd0'), + isNull, + ); + expect(await blobs.readWithPrefsFallback('channel_messages_0'), isNull); + }); + + test('clearLegacySlotHistory keeps the PSK-keyed history', () async { + final s = store(psk: pskA); + await s.saveChannelMessages(0, [chan(1), chan(2)]); + + await s.clearLegacySlotHistory(0); + + final loaded = await s.loadChannelMessages(0); + expect(loaded.map((m) => m.messageId), ['id1', 'id2']); + }); + + test('after a reassignment clear, the new occupant does not adopt the old ' + 'occupant\'s legacy slot history', () async { + // Old occupant A left pre-#194 history under the slot-index key. + await blobs.write( + 'channel_messages_dddddddddd0', + ChannelMessageStore.encodeHistoryForTest([chan(1, text: 'old-A')]), + ); + + // Slot 0 is reassigned to channel B: the connector purges the legacy + // slot keys (setChannel, #1063). + await store(psk: pskB).clearLegacySlotHistory(0); + + // Channel B's first load must not inherit A's messages via the one-time + // slot-index adoption. + expect(await store(psk: pskB).loadChannelMessages(0), isEmpty); + }); + + test('the outgoing occupant\'s history survives a reassignment and comes ' + 'back when the channel is re-added', () async { + // Channel A lives in slot 0 with PSK-keyed history. + final asA = store(psk: pskA); + await asA.saveChannelMessages(0, [chan(1, text: 'kept')]); + + // Slot 0 is reassigned to channel B. + await store(psk: pskB).clearLegacySlotHistory(0); + await store(psk: pskB).saveChannelMessages(0, [chan(9, text: 'b-msg')]); + + // Channel A is re-added (any slot; identity is the PSK, not the slot). + final loaded = await store(psk: pskA).loadChannelMessages(5); + expect(loaded.single.text, 'kept'); + }); + + test('clearChannelMessages (true delete) removes the PSK-keyed history ' + 'and the legacy index key', () async { + final s = store(psk: pskA); + await s.saveChannelMessages(0, [chan(1)]); + await blobs.write( + 'channel_messages_dddddddddd0', + ChannelMessageStore.encodeHistoryForTest([chan(2)]), + ); + + await s.clearChannelMessages(0); + + expect(await s.loadChannelMessages(0), isEmpty); + expect( + await blobs.readWithPrefsFallback('channel_messages_dddddddddd0'), + isNull, + ); + }); +} From 3d40da28f2841ff727e7f59360ebf0f1bed2fe14 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:27:40 -0500 Subject: [PATCH 3/6] test(#1064): end-to-end slot-shuffle scenarios + slot-level ingress hold Integration tests for Feature #1061 across Epics A (#1062) and B (#1063): the #1060 bug-validation scenario (wipe + re-import with shuffled slots: list matches device, no misfiled or mis-rendered message, notify modes evaluate against the right PSKs), a manual device-side reorder (history follows the channel identity to its new slot), and a flaky sync mid-reconnect (held traffic files only after a confirming sync). Writing them exposed one gap: _flushHeldChannelFrames documented that a frame for a still-unconfirmed slot re-holds, but the handler only gated on the list-level barrier, so after a partial sync such a message would file by raw index against an unknown identity and persist under the legacy index key. _handleIncomingChannelMessage now re-holds it until a sync confirms the slot. Test plumbing: channelNotifyProbeForTest observes the notify decision (slot, label, PSK, mode) without reaching the NotificationService singleton; wireMessageStoreForTest wires the message store the way the SELF_INFO handshake does. Issue: #1064 Co-Authored-By: Claude Fable 5 --- lib/connector/meshcore_connector.dart | 45 +++ .../channel_slot_resync_integration_test.dart | 291 ++++++++++++++++++ 2 files changed, 336 insertions(+) create mode 100644 test/connector/channel_slot_resync_integration_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 7f554189..b30b2df0 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -3290,6 +3290,16 @@ class MeshCoreConnector extends ChangeNotifier { @visibleForTesting void setSelfPublicKeyForTest(Uint8List key) => _selfPublicKey = key; + /// Wires the channel message store the way the SELF_INFO handshake does + /// (device scoping + PSK resolver), so integration tests (#1064) exercise + /// the real PSK-keyed persistence path. Call after [setSelfPublicKeyForTest]. + @visibleForTesting + void wireMessageStoreForTest() { + _channelMessageStore.setPublicKeyHex = selfPublicKeyHex; + _channelMessageStore.channelPskResolver = (index) => + _findChannelByIndex(index)?.pskHex; + } + @visibleForTesting static bool shouldResetStateAfterTcpConnectAbort({ required MeshCoreConnectionState state, @@ -4068,6 +4078,20 @@ class MeshCoreConnector extends ChangeNotifier { @visibleForTesting void Function(Uint8List data)? sendFrameOverrideForTest; + /// Observes [_maybeNotifyChannelMessage]'s decision: the slot, the display + /// label, and the PSK + mode the notification was evaluated against (null + /// psk/mode = suppressed because the slot was unconfirmed). Lets tests + /// assert notify routing (#1064) without reaching the NotificationService + /// singleton. + @visibleForTesting + void Function( + int channelIndex, + String channelName, + String? pskHex, + ChannelNotifyMode? mode, + )? + channelNotifyProbeForTest; + @visibleForTesting void setConnectedForTest() => _state = MeshCoreConnectionState.connected; @@ -9401,12 +9425,19 @@ class MeshCoreConnector extends ChangeNotifier { 'unconfirmed, its notify mode cannot be resolved', tag: 'ChannelSync', ); + channelNotifyProbeForTest?.call(channelIndex, label, null, null); return; } final mode = _appSettingsService!.channelNotifyMode( devicePrefix: selfPublicKeyHex, pskHex: slotChannel?.pskHex, ); + channelNotifyProbeForTest?.call( + channelIndex, + label, + slotChannel?.pskHex, + mode, + ); switch (mode) { case ChannelNotifyMode.off: return; @@ -9453,6 +9484,20 @@ class MeshCoreConnector extends ChangeNotifier { } final parsed = ChannelMessage.fromFrame(frame); if (parsed != null && parsed.channelIndex != null) { + // #1062 fail-closed, slot-level: the list is synced but THIS slot never + // confirmed. Filing by index would attach the message to an unknown + // identity and persist it under the legacy index key, so re-hold until + // a sync confirms the slot (found by the #1064 integration tests). + if (isConnected && + _unconfirmedChannelSlots.contains(parsed.channelIndex)) { + _holdChannelFrame( + _heldChannelMsgFrames, + frame, + 'message', + bounded: false, + ); + return; + } // Device-composed (outgoing) messages legitimately carry our own name and // no path; don't let the self-echo guard drop them (#429 part B). if (!parsed.isOutgoing && diff --git a/test/connector/channel_slot_resync_integration_test.dart b/test/connector/channel_slot_resync_integration_test.dart new file mode 100644 index 00000000..b7b633a1 --- /dev/null +++ b/test/connector/channel_slot_resync_integration_test.dart @@ -0,0 +1,291 @@ +// #1064 (Epic C of #1061): end-to-end slot-shuffle scenarios across Epic A +// (#1062, fail-closed sync + ingress barrier) and Epic B (#1063, per-slot +// state never crosses identities). The first test is the #1060 bug-validation +// scenario: a wipe + config re-import rearranged the device's channel slots, +// #wardriving notified with its mode off, and #test messages rendered inside +// the private channel. + +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/models/app_settings.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/services/app_settings_service.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/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({ + required int index, + required String name, + required int pskSeed, +}) { + final frame = Uint8List(50); + frame[0] = respCodeChannelInfo; + frame[1] = index; + final nameBytes = name.codeUnits; + for (var i = 0; i < nameBytes.length && i < 31; i++) { + frame[2 + i] = nameBytes[i]; + } + for (var i = 0; i < 16; i++) { + frame[34 + i] = (pskSeed + i) & 0xFF; + } + return frame; +} + +Uint8List _v3ChannelMsgFrame({required int channelIdx, String text = 'A: hi'}) { + return Uint8List.fromList([ + respCodeChannelMsgRecvV3, + 0, 0, 0, + channelIdx, + 1, // path_len: 1 hop, width 1 + txtTypePlain, + 0x40, 0xE2, 0x01, 0x00, + ...text.codeUnits, + ]); +} + +Channel _channel(int index, String name, int pskSeed) { + final psk = Uint8List.fromList( + List.generate(16, (i) => (pskSeed + i) & 0xFF), + ); + return Channel(index: index, name: name, psk: psk); +} + +typedef _NotifyDecision = ({ + int channelIndex, + String channelName, + String? pskHex, + ChannelNotifyMode? mode, +}); + +Future _settle([int turns = 25]) async { + for (var i = 0; i < turns; i++) { + await Future.delayed(Duration.zero); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late OffbandDatabase db; + late AppSettingsService settings; + late MeshCoreConnector c; + late List<_NotifyDecision> notifyDecisions; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + settings = AppSettingsService(); + await settings.loadSettings(); + + c = MeshCoreConnector(); + c.initialize( + retryService: MessageRetryService(), + pathHistoryService: PathHistoryService(StorageService()), + appSettingsService: settings, + ); + c.sendFrameOverrideForTest = (_) {}; + c.setConnectedForTest(); + c.setSelfPublicKeyForTest( + Uint8List.fromList(List.generate(32, (i) => i)), + ); + c.wireMessageStoreForTest(); + + notifyDecisions = []; + c.channelNotifyProbeForTest = (index, name, pskHex, mode) { + notifyDecisions.add(( + channelIndex: index, + channelName: name, + pskHex: pskHex, + mode: mode, + )); + }; + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Future syncWith(List deviceArrangement, {int? max}) async { + await c.getChannels( + force: true, + maxChannels: max ?? deviceArrangement.length, + ); + for (final ch in deviceArrangement) { + c.handleFrameForTest( + _channelInfoFrame(index: ch.index, name: ch.name, pskSeed: ch.psk[0]), + ); + await _settle(2); + } + await _settle(); + } + + test('#1060 bug validation: wipe + re-import with shuffled slots', () async { + // Before the wipe this radio had: slot0 #wardriving (notify OFF), + // slot1 #test, slot2 the private channel (an old conversation on screen). + final wardriving = _channel(0, 'wardriving', 40); + final testCh = _channel(1, 'test', 50); + final private = _channel(2, 'Private', 60); + c.seedCachedChannelsForTest([wardriving, testCh, private]); + await settings.setChannelNotifyMode( + devicePrefix: c.selfPublicKeyHex, + pskHex: wardriving.pskHex, + channelName: wardriving.name, + mode: ChannelNotifyMode.off, + ); + c.channelMessagesForTest[2] = [ + ChannelMessage( + senderName: 'friend', + text: 'old private talk', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000), + isOutgoing: false, + channelIndex: 2, + messageId: 'old-private', + ), + ]; + + // The re-imported config put the same channels in DIFFERENT slots. + await syncWith([ + _channel(0, 'test', 50), + _channel(1, 'Private', 60), + _channel(2, 'wardriving', 40), + ]); + + // The list matches the device, and every slot's change was surfaced. + expect(c.channels.map((ch) => ch.name), ['test', 'Private', 'wardriving']); + expect(c.slotIdentityChanges, hasLength(3)); + expect(c.unconfirmedChannelSlots, isEmpty); + + // The old private conversation did not stay behind in slot 2, which + // #wardriving now occupies. + expect(c.channelMessagesForTest[2] ?? const [], isEmpty); + + // A #test message files under #test's slot and is evaluated against + // #test's PSK (default mode), not against whatever used to live there. + c.handleFrameForTest(_v3ChannelMsgFrame(channelIdx: 0, text: 'B: to test')); + await _settle(); + expect(c.channelMessagesForTest[0]!.single.text, 'to test'); + expect( + c.channelMessagesForTest[1] ?? const [], + isEmpty, + reason: '#test traffic must not render inside the private channel', + ); + final testDecision = notifyDecisions.single; + expect(testDecision.channelName, 'test'); + expect(testDecision.pskHex, testCh.pskHex); + expect(testDecision.mode, ChannelNotifyMode.all); + + // A #wardriving message follows #wardriving's OFF mode to its NEW slot: + // the #1060 complaint was notifications firing with the mode off. + notifyDecisions.clear(); + c.handleFrameForTest(_v3ChannelMsgFrame(channelIdx: 2, text: 'B: war')); + await _settle(); + expect(c.channelMessagesForTest[2]!.single.text, 'war'); + final warDecision = notifyDecisions.single; + expect(warDecision.pskHex, wardriving.pskHex); + expect( + warDecision.mode, + ChannelNotifyMode.off, + reason: 'the OFF mode belongs to the PSK and must ride along to slot 2', + ); + }); + + test('manual reorder on the device: history follows the channel, ' + 'not the slot', () async { + // First sync: Alpha in slot 0, Beta in slot 1. A message lands in Alpha + // and is persisted under Alpha's PSK identity. + await syncWith([_channel(0, 'Alpha', 10), _channel(1, 'Beta', 30)]); + c.handleFrameForTest( + _v3ChannelMsgFrame(channelIdx: 0, text: 'A: hello alpha'), + ); + await _settle(); + expect(c.channelMessagesForTest[0]!.single.text, 'hello alpha'); + // Let the unawaited persistence land before the reorder. + await Future.delayed(const Duration(milliseconds: 50)); + + // The operator swaps the slots on the device; the client re-syncs. + await syncWith([_channel(0, 'Beta', 30), _channel(1, 'Alpha', 10)]); + await Future.delayed(const Duration(milliseconds: 50)); + await _settle(); + + expect(c.channels.map((ch) => ch.name), ['Beta', 'Alpha']); + expect( + c.channelMessagesForTest[0] ?? const [], + isEmpty, + reason: "Alpha's conversation must not render under Beta", + ); + expect( + (c.channelMessagesForTest[1] ?? const []).map( + (m) => m.text, + ), + ['hello alpha'], + reason: "Alpha's PSK-keyed history reloads at its new slot", + ); + }); + + test('flaky sync mid-reconnect: held traffic files only after a ' + 'confirming sync, against the right PSK', () async { + final alpha = _channel(0, 'Alpha', 10); + final beta = _channel(1, 'Beta', 30); + c.seedCachedChannelsForTest([alpha, beta]); + await settings.setChannelNotifyMode( + devicePrefix: c.selfPublicKeyHex, + pskHex: beta.pskHex, + channelName: beta.name, + mode: ChannelNotifyMode.off, + ); + + // The sync answers slot 0, a message for slot 1 arrives mid-sync, and + // slot 1 never answers. + await c.getChannels(maxChannels: 2); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Alpha', pskSeed: 10), + ); + await _settle(2); + c.handleFrameForTest(_v3ChannelMsgFrame(channelIdx: 1, text: 'B: held')); + for (var i = 0; i <= 3; i++) { + c.handleChannelSyncTimeoutForTest(1); + await _settle(2); + } + await _settle(); + + expect(c.unconfirmedChannelSlots, {1}); + expect( + c.channelMessagesForTest[1], + isNull, + reason: 'a message for an unconfirmed slot must not file by raw index', + ); + expect( + notifyDecisions.where((d) => d.channelIndex == 1 && d.mode != null), + isEmpty, + reason: 'no notify decision can be made for an unconfirmed slot', + ); + + // The reconnect-style retry confirms both slots; the held message now + // files, and Beta's OFF mode is evaluated against Beta's own PSK. + notifyDecisions.clear(); + await syncWith([alpha, beta]); + + expect(c.unconfirmedChannelSlots, isEmpty); + expect(c.channels.map((ch) => ch.name), ['Alpha', 'Beta']); + expect(c.channelMessagesForTest[1]!.single.text, 'held'); + final decision = notifyDecisions.single; + expect(decision.channelIndex, 1); + expect(decision.pskHex, beta.pskHex); + expect(decision.mode, ChannelNotifyMode.off); + }); +} From 015f3fb94bc4d84849c9b4e2253a2f6b79f5f96d Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:30:17 -0500 Subject: [PATCH 4/6] docs(#1064): feature 1061 PLAN and OUTCOMES The plan of record (four approved parts, the Epic B re-scope) and the outcomes: what each Epic shipped, the slot-level ingress gap the integration tests exposed, the positive and negative test evidence, and what stays open until the owner's hardware pass. Issue: #1064 Co-Authored-By: Claude Fable 5 --- .../1061-channel-slot-resync/OUTCOMES.md | 37 ++++++++++++++++++ .../1061-channel-slot-resync/PLAN.md | 39 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md create mode 100644 docs/initiatives/standalone/1061-channel-slot-resync/PLAN.md diff --git a/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md new file mode 100644 index 00000000..c46b5541 --- /dev/null +++ b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md @@ -0,0 +1,37 @@ +# Feature #1061 channel slot resync truth: OUTCOMES + +Status: BUILT and machine-verified; awaiting the owner's hardware test, then PRs. Branch stack: `feat/1062-channel-sync-truth` (Epic A) ← `feat/1063-message-state-hardening` (Epics B + C). + +## What was built +| Epic | Commit | Content | +|---|---|---| +| A #1062 | `c2f599e3` | fail-closed atomic sync (no backfill, unconfirmed slots tracked + bannered with Retry, cache kept on holes), ingress barrier (messages held unbounded, raw sniffs bounded 64, flush post-sync), per-slot PSK identity diff (UI notice + warn log), unread preserved only on same PSK, fail-closed `_findChannelByIndex`, notification suppression for unconfirmed slots, self-retry on failed live sync | +| B #1063 | `0d19c3c7` | in-memory conversation dropped + reloaded under the new PSK on slot identity change; setChannel reassignment clear narrowed to legacy slot keys (PSK history survives re-add; deleteChannel keeps the full clear); write-side index fallback escalated to an error naming the orphaning consequence; stale #193-era comments corrected, setChannel/resolver interplay documented | +| C #1064 | `0f8fcce1` | the three integration scenarios below, the notify-decision test probe, store wiring test hook, and one fix the tests exposed (next section) | + +## Gap found by the integration tests (fixed in `0f8fcce1`) +Epic A's flush documented that a held frame for a still-unconfirmed slot re-holds, but the handler only gated on the list-level barrier: after a PARTIAL sync completed, a held message for an unconfirmed slot would have filed by raw index against an unknown identity and persisted under the legacy index key. `_handleIncomingChannelMessage` now re-holds such frames until a sync confirms the slot. This is the "prove the check can fail" discipline paying for itself; the flaky-sync scenario below fails without the fix. + +## Evidence +Machine verification, all on the stacked branch: +- `flutter analyze` clean on every touched file. +- Unit tests: 7 sync-truth tests (`test/connector/channel_sync_truth_test.dart`), 5 store identity tests (`test/storage/channel_message_store_identity_test.dart`). +- Integration tests (`test/connector/channel_slot_resync_integration_test.dart`): + 1. **#1060 bug validation (wipe + re-import, all three slots shuffled):** post-sync list matches the device exactly; all three identity changes surfaced; the old private conversation does not stay behind under #wardriving; a #test message files under #test and is notify-evaluated against #test's PSK (mode `all`); a #wardriving message is evaluated against #wardriving's PSK and its OFF mode rides along to the new slot. The reported symptoms (muted channel notifying, #test rendering in the private channel) cannot reproduce. + 2. **Manual device-side reorder:** a message persisted under Alpha's PSK follows Alpha to its new slot after the re-sync; nothing renders under Beta. + 3. **Flaky sync mid-reconnect:** a message for a never-confirmed slot is held, not filed by raw index, and no notify decision is made for it; after a confirming re-sync it files once, against the right PSK and mode. +- **Negative evidence:** with Epic B's drop/reload and the slot-level re-hold reverted in the working tree, all three scenarios fail (`+0 -3`) on exactly the guarded assertions; restored, all pass. The checks can fail. +- Full suite at Epic B: 1791 passed / 1 skipped, exit 0. Full suite at Epic C: 1794 passed / 1 skipped, exit 0. + +## Decisions logged +- Epic B re-scope approved by the owner 2026-11-03 ("Agree, proceed"); storage was already PSK-keyed since #194, so no migration was needed. +- Already-miskeyed rows from the #1060 window stay as-is: not mechanically separable, and the owner's standing history-loss bar is deliberately low. Say the word and a per-radio clear can be added instead. +- setChannel reassignment now PRESERVES the outgoing occupant's PSK-keyed history (only legacy slot keys are purged). Re-adding a channel later restores its messages; this strengthens #194's intent and the diff is one call site, flagged for owner review on the Epic B PR. + +## Open until the owner closes them +- Hardware test of the combined stack (the #1060 recovery sequence on the T1000e: wipe, re-import, reconnect, one sync). +- The user-reported problem the owner logged this feature against: its one-liner / issue number is still pending and will be linked under #1063/#1064 when provided. +- PRs + merges after the hardware pass (stacked: A into dev, B+C into A's branch or rebased per owner preference). +- #1060 closes only after the owner confirms on hardware. + +Agent: TurquoiseBridge (session 82d77b2f) diff --git a/docs/initiatives/standalone/1061-channel-slot-resync/PLAN.md b/docs/initiatives/standalone/1061-channel-slot-resync/PLAN.md new file mode 100644 index 00000000..ead837e6 --- /dev/null +++ b/docs/initiatives/standalone/1061-channel-slot-resync/PLAN.md @@ -0,0 +1,39 @@ +# Feature PLAN: channel slot resync truth (#1060 class) + +| | | +|---|---| +| **Feature** | [#1061](https://github.com/OffbandMesh/meshcore-client/issues/1061) · Citadel `meshcore-open-rwr` | +| **Fixes** | [#1060](https://github.com/OffbandMesh/meshcore-client/issues/1060) (P0): wipe + config re-import shuffled channel slots; notifications fired for a muted channel and messages rendered inside the wrong conversation | +| **Owner** | @Strycher | +| **Approved** | 2026-11-02 in chat: "Agree with all 4, don't hold on 4, do it now." Epic B re-scope approved 2026-11-03: "Agree, proceed." | + +## At a glance +- **What:** make the device's channel list the only truth the client ever acts on, and make every piece of per-slot client state follow the channel's PSK identity instead of its reusable slot index. +- **Why:** #1060. The radio is authoritative for slot assignments; after a wipe + re-import the same channels can sit in different slots, and any client state keyed by slot silently attaches to the wrong channel. +- **Done when:** the integration scenarios pass (positive and negative), the #1060 reporter's sequence cannot recur, and the owner approves the OUTCOMES. + +## 1. Diagnosis (#1060, verified in code) +Three routes let a stale slot map poison live behavior: +1. **Backfill:** the channel sync restored unanswered slots from `_previousChannelsCache`, so a shuffled device list came back part-fresh, part-stale. +2. **Index filing:** raw-RX and message ingress filed by slot index through the stale list. +3. **Poisoned resolver:** notify modes and persisted history are PSK-keyed (#839, #194), but both resolve PSKs through `_findChannelByIndex` - which consulted the stale list, so correct identity keying was fed wrong identities. + +## 2. The four approved parts → Epics +| Part | Epic | Scope | +|---|---|---| +| 1. Fail-closed, atomic channel sync | A [#1062](https://github.com/OffbandMesh/meshcore-client/issues/1062) | never backfill an unanswered slot; unconfirmed slots tracked + surfaced (banner w/ Retry); cache not overwritten on holes; self-retry on a failed live sync | +| 2. Ingress barrier | A #1062 | no live channel frame files until THIS connection confirms the list; pull-based message frames held unbounded (the radio already popped them), raw sniffs bounded at 64; held frames flush post-sync | +| 3. Per-slot identity diff | A #1062 | PSK diff per slot against the last truth; identity changes surfaced in UI + log; unread preserved only on same PSK; unconfirmed slots fail closed in `_findChannelByIndex` and suppress notifications | +| 4. Identity-keyed message state | B [#1063](https://github.com/OffbandMesh/meshcore-client/issues/1063) | RE-SCOPED (see below) | +| Validation | C [#1064](https://github.com/OffbandMesh/meshcore-client/issues/1064) | end-to-end scenarios, the #1060 bug-validation test, this folder's OUTCOMES.md | + +## 3. Epic B re-scope (approved 2026-11-03) +Part 4 was planned as "re-key channel_message_store by PSK with migration" from a stale #193-era comment. The store has been PSK-keyed since #194; the incident's cross-wiring came from the poisoned resolver (route 3), which Epic A fixes. Epic B therefore shrank to: +1. drop a slot's in-memory `_channelMessages` entry on identity change and reload it under the new identity's PSK; +2. harden the store's slot-index write fallback (error log naming the orphaning consequence); +3. narrow setChannel's reassignment clear to the LEGACY slot keys only, so the outgoing occupant's PSK-keyed history survives and returns if the channel is re-added; +4. correct the stale #193-era comments and document the setChannel/resolver interplay. + +Already-miskeyed rows from the #1060 window stay as-is (not mechanically separable; owner's standing low history-loss bar). + +Agent: TurquoiseBridge (session 82d77b2f) From 3a6e6473dee160bae22929b34181e42eba129214 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 3 Nov 2026 02:26:32 -0500 Subject: [PATCH 5/6] docs(#1064): record the owner's push/PR authorization and post-rebase SHAs The owner waived the pre-PR hardware gate for feature 1061 (no way to reproduce on demand); validation moves to live testing after merge. Merges still require the explicit per-PR grant. Co-Authored-By: Claude Fable 5 --- .../1061-channel-slot-resync/OUTCOMES.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md index c46b5541..9ac25a7c 100644 --- a/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md +++ b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md @@ -1,15 +1,15 @@ # Feature #1061 channel slot resync truth: OUTCOMES -Status: BUILT and machine-verified; awaiting the owner's hardware test, then PRs. Branch stack: `feat/1062-channel-sync-truth` (Epic A) ← `feat/1063-message-state-hardening` (Epics B + C). +Status: BUILT and machine-verified; PRs opened on the owner's word (decision below), validation moves to live testing after merge. Branch stack: `feat/1062-channel-sync-truth` (Epic A) ← `feat/1063-message-state-hardening` (Epics B + C), rebased onto dev `180c01e6`. ## What was built | Epic | Commit | Content | |---|---|---| -| A #1062 | `c2f599e3` | fail-closed atomic sync (no backfill, unconfirmed slots tracked + bannered with Retry, cache kept on holes), ingress barrier (messages held unbounded, raw sniffs bounded 64, flush post-sync), per-slot PSK identity diff (UI notice + warn log), unread preserved only on same PSK, fail-closed `_findChannelByIndex`, notification suppression for unconfirmed slots, self-retry on failed live sync | -| B #1063 | `0d19c3c7` | in-memory conversation dropped + reloaded under the new PSK on slot identity change; setChannel reassignment clear narrowed to legacy slot keys (PSK history survives re-add; deleteChannel keeps the full clear); write-side index fallback escalated to an error naming the orphaning consequence; stale #193-era comments corrected, setChannel/resolver interplay documented | -| C #1064 | `0f8fcce1` | the three integration scenarios below, the notify-decision test probe, store wiring test hook, and one fix the tests exposed (next section) | +| A #1062 | `da08b7eb` | fail-closed atomic sync (no backfill, unconfirmed slots tracked + bannered with Retry, cache kept on holes), ingress barrier (messages held unbounded, raw sniffs bounded 64, flush post-sync), per-slot PSK identity diff (UI notice + warn log), unread preserved only on same PSK, fail-closed `_findChannelByIndex`, notification suppression for unconfirmed slots, self-retry on failed live sync | +| B #1063 | `b658fe14` | in-memory conversation dropped + reloaded under the new PSK on slot identity change; setChannel reassignment clear narrowed to legacy slot keys (PSK history survives re-add; deleteChannel keeps the full clear); write-side index fallback escalated to an error naming the orphaning consequence; stale #193-era comments corrected, setChannel/resolver interplay documented | +| C #1064 | `2a9d1e16` | the three integration scenarios below, the notify-decision test probe, store wiring test hook, and one fix the tests exposed (next section) | -## Gap found by the integration tests (fixed in `0f8fcce1`) +## Gap found by the integration tests (fixed in `2a9d1e16`) Epic A's flush documented that a held frame for a still-unconfirmed slot re-holds, but the handler only gated on the list-level barrier: after a PARTIAL sync completed, a held message for an unconfirmed slot would have filed by raw index against an unknown identity and persisted under the legacy index key. `_handleIncomingChannelMessage` now re-holds such frames until a sync confirms the slot. This is the "prove the check can fail" discipline paying for itself; the flaky-sync scenario below fails without the fix. ## Evidence @@ -27,11 +27,12 @@ Machine verification, all on the stacked branch: - Epic B re-scope approved by the owner 2026-11-03 ("Agree, proceed"); storage was already PSK-keyed since #194, so no migration was needed. - Already-miskeyed rows from the #1060 window stay as-is: not mechanically separable, and the owner's standing history-loss bar is deliberately low. Say the word and a per-radio clear can be added instead. - setChannel reassignment now PRESERVES the outgoing occupant's PSK-keyed history (only legacy slot keys are purged). Re-adding a channel later restores its messages; this strengthens #194's intent and the diff is one call site, flagged for owner review on the Epic B PR. +- Owner, 2026-11-03 in chat: "I don't have a way to reproduce right now. Push/pr if the work is done, we will validate in live testing." The pre-PR hardware gate is waived for this feature; validation moves to live testing. Merges still require the explicit per-PR grant. ## Open until the owner closes them -- Hardware test of the combined stack (the #1060 recovery sequence on the T1000e: wipe, re-import, reconnect, one sync). +- Live-testing validation after merge (the #1060 recovery sequence: wipe, re-import, reconnect, one sync). The owner cannot reproduce on demand right now, so this is observational. - The user-reported problem the owner logged this feature against: its one-liner / issue number is still pending and will be linked under #1063/#1064 when provided. -- PRs + merges after the hardware pass (stacked: A into dev, B+C into A's branch or rebased per owner preference). -- #1060 closes only after the owner confirms on hardware. +- Merges of the stacked PRs (A into dev, then B+C) on the owner's explicit grant. +- #1060 closes only after the owner confirms the fix in live use. Agent: TurquoiseBridge (session 82d77b2f) From 12154c61f2e963cacb3a14d52d013492262eebb4 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 3 Nov 2026 02:40:44 -0500 Subject: [PATCH 6/6] fix(#1063): close the adversarial-review findings on the 1061 stack Gemini gate (gemini-2.5-pro) on the pre-push stack, four findings: - Held channel message frames are now keyed per radio: verifying the unbounded-growth finding exposed that frames held from radio X would have flushed into radio Y's conversations after a radio switch. A parked radio's frames flush when that radio next completes a sync. No cap is added: held frames are popped messages, dropping one is guaranteed loss, and growth is traffic-bounded (<=172 bytes/frame). - _loadChannelMessages merges messages that arrived during the disk read instead of clobbering the list, so the slot-identity reload cannot hide a message the held-frame flush just filed (disk was never at risk: saves merge by identity, #343). - sendChannelMessage refuses the write for a slot this connection has not confirmed (the persisted copy would fall back to the legacy slot-index key and be orphaned), and the chat screen surfaces a persistent error at every send path instead of greying anything. New English UI string; untranslated.json regenerated (#1063). Three integration tests cover the fixes (#1064); with the guards behaviorally disabled exactly those three fail (+3 -3). Full suite 1807 passed / 1 skipped. OUTCOMES.md records the gate and dispositions. Co-Authored-By: Claude Fable 5 --- .../1061-channel-slot-resync/OUTCOMES.md | 9 +- lib/connector/meshcore_connector.dart | 63 ++++++++- lib/l10n/app_en.arb | 1 + lib/l10n/app_localizations.dart | 6 + lib/l10n/app_localizations_bg.dart | 4 + lib/l10n/app_localizations_de.dart | 4 + lib/l10n/app_localizations_en.dart | 4 + lib/l10n/app_localizations_es.dart | 4 + lib/l10n/app_localizations_fr.dart | 4 + lib/l10n/app_localizations_hu.dart | 4 + lib/l10n/app_localizations_it.dart | 4 + lib/l10n/app_localizations_ja.dart | 4 + lib/l10n/app_localizations_ko.dart | 4 + lib/l10n/app_localizations_nl.dart | 4 + lib/l10n/app_localizations_pl.dart | 4 + lib/l10n/app_localizations_pt.dart | 4 + lib/l10n/app_localizations_ru.dart | 4 + lib/l10n/app_localizations_sk.dart | 4 + lib/l10n/app_localizations_sl.dart | 4 + lib/l10n/app_localizations_sv.dart | 4 + lib/l10n/app_localizations_uk.dart | 4 + lib/l10n/app_localizations_zh.dart | 4 + lib/screens/channel_chat_screen.dart | 27 +++- .../channel_slot_resync_integration_test.dart | 124 ++++++++++++++++++ untranslated.json | 17 +++ 25 files changed, 307 insertions(+), 12 deletions(-) diff --git a/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md index 9ac25a7c..3a98ea0c 100644 --- a/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md +++ b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md @@ -12,6 +12,13 @@ Status: BUILT and machine-verified; PRs opened on the owner's word (decision bel ## Gap found by the integration tests (fixed in `2a9d1e16`) Epic A's flush documented that a held frame for a still-unconfirmed slot re-holds, but the handler only gated on the list-level barrier: after a PARTIAL sync completed, a held message for an unconfirmed slot would have filed by raw index against an unknown identity and persisted under the legacy index key. `_handleIncomingChannelMessage` now re-holds such frames until a sync confirms the slot. This is the "prove the check can fail" discipline paying for itself; the flaky-sync scenario below fails without the fix. +## Gemini adversarial gate (gemini-2.5-pro, 2026-11-03, at the pre-push stack head) +Four findings, all addressed before push: +1. **HIGH, unbounded held frames:** cap deliberately NOT added (held frames are popped messages; dropping one is guaranteed loss; growth is traffic-bounded at <=172 bytes/frame and drains on the next confirming sync). Verifying it exposed a sharper defect the review did not name: held frames survived a radio SWITCH and would have flushed into the other radio's conversations. Fixed: held message frames are keyed per radio and flush only when their own radio completes a sync. +2. **MEDIUM, identity-change reload race:** confirmed for in-memory state only (saves merge by identity, #343). Fixed: `_loadChannelMessages` merges messages that arrived during the disk read instead of clobbering. +3. **MEDIUM, outgoing send on an unconfirmed slot orphans the persisted copy:** confirmed. Fixed: `sendChannelMessage` refuses the write (fail closed, logged) and the chat screen shows a persistent error at every send path. New English UI string, untranslated.json regenerated. +4. **Test gaps:** three integration tests added (race, refused send, cross-radio hold); with the three guards behaviorally disabled, exactly those three fail (+3 -3). + ## Evidence Machine verification, all on the stacked branch: - `flutter analyze` clean on every touched file. @@ -21,7 +28,7 @@ Machine verification, all on the stacked branch: 2. **Manual device-side reorder:** a message persisted under Alpha's PSK follows Alpha to its new slot after the re-sync; nothing renders under Beta. 3. **Flaky sync mid-reconnect:** a message for a never-confirmed slot is held, not filed by raw index, and no notify decision is made for it; after a confirming re-sync it files once, against the right PSK and mode. - **Negative evidence:** with Epic B's drop/reload and the slot-level re-hold reverted in the working tree, all three scenarios fail (`+0 -3`) on exactly the guarded assertions; restored, all pass. The checks can fail. -- Full suite at Epic B: 1791 passed / 1 skipped, exit 0. Full suite at Epic C: 1794 passed / 1 skipped, exit 0. +- Full suite at Epic B: 1791 passed / 1 skipped, exit 0. Full suite at Epic C: 1794 passed / 1 skipped, exit 0. Full suite at the pushed head (post-rebase, post-review fixes): 1807 passed / 1 skipped, exit 0. ## Decisions logged - Epic B re-scope approved by the owner 2026-11-03 ("Agree, proceed"); storage was already PSK-keyed since #194, so no migration was needed. diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index b30b2df0..0ce68841 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -593,9 +593,16 @@ class MeshCoreConnector extends ChangeNotifier { // #1062: ingress barrier. Live channel traffic is held while this // connection's channel list is not yet synced, then flushed, so a message - // is never filed against a guessed slot map. + // is never filed against a guessed slot map. Held MESSAGE frames are keyed + // by the radio that delivered them (#1063 review): they survive reconnects + // because the radio already popped them, but a switch to a DIFFERENT radio + // must not flush them into its conversations. A parked radio's frames flush + // when that radio next completes a sync; '' holds frames from before the + // connection identified itself and is adopted by the next flush. bool _channelListSynced = false; - final List _heldChannelMsgFrames = []; + final Map> _heldChannelMsgFramesByRadio = {}; + List get _heldChannelMsgFrames => + _heldChannelMsgFramesByRadio.putIfAbsent(selfPublicKeyHex, () => []); final List _heldRawChannelFrames = []; static const int _maxHeldChannelFrames = 64; @@ -2355,9 +2362,24 @@ class MeshCoreConnector extends ChangeNotifier { ); if (allMessages.isNotEmpty) { // Keep only the most recent N messages in memory to bound memory usage - final windowedMessages = allMessages.length > _messageWindowSize - ? allMessages.sublist(allMessages.length - _messageWindowSize) - : allMessages; + final windowedMessages = List.from( + allMessages.length > _messageWindowSize + ? allMessages.sublist(allMessages.length - _messageWindowSize) + : allMessages, + ); + + // A message can land in memory while this load is reading the store + // (the slot-identity reload racing a flushed held frame, #1063 review). + // The store save merges, so disk already has it; keep it visible too + // instead of clobbering the list with the pre-arrival history. + final current = _channelMessages[channelIndex]; + if (current != null) { + for (final m in current) { + if (_findChannelRepeatIndex(windowedMessages, m) < 0) { + windowedMessages.add(m); + } + } + } _channelMessages[channelIndex] = windowedMessages; notifyListeners(); @@ -4198,8 +4220,9 @@ class MeshCoreConnector extends ChangeNotifier { _previousChannelsCache.clear(); // #1062: a new connection starts with an unconfirmed list. Held MESSAGE // frames are kept: the radio already popped them from its queue, so they - // exist nowhere else, and the next confirmed sync files them. Raw sniff - // frames are lossy observations; a dead connection's are stale. + // exist nowhere else, and the holding radio's next confirmed sync files + // them (per-radio, so a radio switch cannot leak them, #1063 review). + // Raw sniff frames are lossy observations; a dead connection's are stale. _channelListSynced = false; _unconfirmedChannelSlots.clear(); _slotIdentityChanges.clear(); @@ -5733,6 +5756,14 @@ class MeshCoreConnector extends ChangeNotifier { return ts; } + /// Whether an outgoing write for [channelIndex] is allowed (#1063 review). + /// False while this connection has not confirmed the slot: the PSK resolver + /// would return null and the persisted copy would fall back to the legacy + /// slot-index key, orphaning it (adoption only runs on an empty PSK key). + /// Callers must refuse the write and tell the user why, not grey a button. + bool canSendOnChannel(int channelIndex) => + _channelListSynced && !_unconfirmedChannelSlots.contains(channelIndex); + Future sendChannelMessage( Channel channel, String text, { @@ -5741,6 +5772,16 @@ class MeshCoreConnector extends ChangeNotifier { String? translationModelId, }) async { if (!isConnected || text.isEmpty) return; + if (!canSendOnChannel(channel.index)) { + // Fail closed at the write, loudly: the message would persist under an + // unknown identity. The UI surfaces this via [canSendOnChannel]. + _appDebugLogService?.error( + 'Refused to send on channel slot ${channel.index}: the slot is not ' + 'confirmed by this connection (#1063). Retry the channel sync.', + tag: 'ChannelSync', + ); + return; + } // Check if this is a reaction - if so, process it immediately instead of adding as a message final reactionInfo = ReactionHelper.parseReaction(text); @@ -6512,6 +6553,14 @@ class MeshCoreConnector extends ChangeNotifier { /// Runs after [_channelListSynced] flips true, so the handlers file against /// the fresh list; a frame whose slot is still unconfirmed re-holds. void _flushHeldChannelFrames() { + // Frames held before this connection learned its radio key belong to this + // connection (nothing flows before the handshake); adopt them first. + if (selfPublicKeyHex.isNotEmpty) { + final unattributed = _heldChannelMsgFramesByRadio.remove(''); + if (unattributed != null) { + _heldChannelMsgFrames.insertAll(0, unattributed); + } + } if (_heldChannelMsgFrames.isEmpty && _heldRawChannelFrames.isEmpty) return; final msgFrames = List.from(_heldChannelMsgFrames); final rawFrames = List.from(_heldRawChannelFrames); diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 317b1ee5..fc5a4677 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1205,6 +1205,7 @@ } }, "channel_senderAddNotConnected": "Not connected to a radio, so this sender can't be added yet", + "channel_slotUnconfirmedSendBlocked": "Message not sent: the radio hasn't confirmed this channel slot yet. Retry the channel sync, then send again.", "channel_senderAddFailed": "Couldn't add this sender: {error}", "@channel_senderAddFailed": { "placeholders": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 3044aeca..c64ec3c1 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3730,6 +3730,12 @@ abstract class AppLocalizations { /// **'Not connected to a radio, so this sender can\'t be added yet'** String get channel_senderAddNotConnected; + /// No description provided for @channel_slotUnconfirmedSendBlocked. + /// + /// In en, this message translates to: + /// **'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'** + String get channel_slotUnconfirmedSendBlocked; + /// No description provided for @channel_senderAddFailed. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index b1b6f5ae..1de8aee6 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -2137,6 +2137,10 @@ class AppLocalizationsBg extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 77afe12f..2ff95514 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -2135,6 +2135,10 @@ class AppLocalizationsDe extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 39478abc..a54bed81 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -2106,6 +2106,10 @@ class AppLocalizationsEn extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 2183176d..9d2ecb51 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -2132,6 +2132,10 @@ class AppLocalizationsEs extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 7f729f47..e5765685 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -2139,6 +2139,10 @@ class AppLocalizationsFr extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index a6c3b9a4..68aa77eb 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -2144,6 +2144,10 @@ class AppLocalizationsHu extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 5b4b9d0f..f11a8a5c 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -2134,6 +2134,10 @@ class AppLocalizationsIt extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 74a35229..1fb331a8 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -2069,6 +2069,10 @@ class AppLocalizationsJa extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index cc8b2ad4..9a7c320c 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -2065,6 +2065,10 @@ class AppLocalizationsKo extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 9a206eed..2962b084 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -2122,6 +2122,10 @@ class AppLocalizationsNl extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 846c6b3f..9f412ea4 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -2147,6 +2147,10 @@ class AppLocalizationsPl extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 111aecc5..b65a487e 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -2131,6 +2131,10 @@ class AppLocalizationsPt extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index d2724854..fc66e2db 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -2135,6 +2135,10 @@ class AppLocalizationsRu extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index de469971..324dbb65 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -2124,6 +2124,10 @@ class AppLocalizationsSk extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 77cfd12c..7d2d1f8c 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -2120,6 +2120,10 @@ class AppLocalizationsSl extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index b8fec2a9..5d93902f 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -2115,6 +2115,10 @@ class AppLocalizationsSv extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index b1728c8f..38f71fa0 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -2130,6 +2130,10 @@ class AppLocalizationsUk extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 64f10bc4..9620e163 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -2044,6 +2044,10 @@ class AppLocalizationsZh extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index dd2cfbf4..9ae7fd14 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1771,6 +1771,9 @@ class _ChannelChatScreenState extends State { } // end transform + // Refuse before clearing so the draft survives the refusal. + if (_refuseIfSlotUnconfirmed(connector)) return; + _textController.clear(); _cancelReply(); _textFieldFocusNode.requestFocus(); @@ -1783,6 +1786,21 @@ class _ChannelChatScreenState extends State { ); } + /// #1063: an outgoing write on a slot this connection has not confirmed + /// would persist under an unknown identity and be orphaned, so refuse at + /// the attempt and say why (a sync can confirm the slot seconds later, so + /// greying the composer would mislead). + bool _refuseIfSlotUnconfirmed(MeshCoreConnector connector) { + if (connector.canSendOnChannel(_currentChannel.index)) return false; + showDismissibleSnackBar( + context, + content: Text(context.l10n.channel_slotUnconfirmedSendBlocked), + backgroundColor: Theme.of(context).colorScheme.error, + persist: true, + ); + return true; + } + /// One-click reply quoting the route a message took, hop count + path, /// truncated with … to fit the channel byte budget, fired directly. (#106) void _sendRouteReply(ChannelMessage message) { @@ -1816,6 +1834,7 @@ class _ChannelChatScreenState extends State { if (connector.isChannelCyr2LatEnabled(_currentChannel.index)) { text = Cyr2Lat.encode(text); } + if (_refuseIfSlotUnconfirmed(connector)) return; connector.sendChannelMessage(_currentChannel, text); } @@ -2051,10 +2070,9 @@ class _ChannelChatScreenState extends State { } void _retryChannelMessage(ChannelMessage message) { - context.read().sendChannelMessage( - _currentChannel, - message.text, - ); + final connector = context.read(); + if (_refuseIfSlotUnconfirmed(connector)) return; + connector.sendChannelMessage(_currentChannel, message.text); showDismissibleSnackBar( context, content: Text(context.l10n.chat_sendingAgain), @@ -2229,6 +2247,7 @@ class _ChannelChatScreenState extends State { message.text, ); final reactionText = ReactionHelper.encodeReaction(hash, emojiIndex); + if (_refuseIfSlotUnconfirmed(connector)) return; connector.sendChannelMessage(_currentChannel, reactionText); } diff --git a/test/connector/channel_slot_resync_integration_test.dart b/test/connector/channel_slot_resync_integration_test.dart index b7b633a1..cecbfe89 100644 --- a/test/connector/channel_slot_resync_integration_test.dart +++ b/test/connector/channel_slot_resync_integration_test.dart @@ -288,4 +288,128 @@ void main() { expect(decision.pskHex, beta.pskHex); expect(decision.mode, ChannelNotifyMode.off); }); + + test( + 'identity-change reload does not hide a message flushed meanwhile', + () async { + // Beta builds history at slot 1, then moves to slot 0. A live message for + // slot 0 arrives MID-resync (held), so the flush files it while the + // identity-change reload is still reading the store. Both must be visible + // afterwards: the reload merges, it does not clobber (#1063 review). + await syncWith([_channel(0, 'Alpha', 10), _channel(1, 'Beta', 30)]); + c.handleFrameForTest( + _v3ChannelMsgFrame(channelIdx: 1, text: 'B: beta history'), + ); + await _settle(); + await Future.delayed(const Duration(milliseconds: 50)); + + await c.getChannels(force: true, maxChannels: 2); + // Mid-resync: the barrier is closed, so this is held, and the flush will + // file it in the same turn that starts the slot-0 reload. + c.handleFrameForTest( + _v3ChannelMsgFrame(channelIdx: 0, text: 'B: live during sync'), + ); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Beta', pskSeed: 30), + ); + await _settle(2); + c.handleFrameForTest( + _channelInfoFrame(index: 1, name: 'Alpha', pskSeed: 10), + ); + await _settle(); + await Future.delayed(const Duration(milliseconds: 50)); + await _settle(); + + final slot0Texts = + (c.channelMessagesForTest[0] ?? const []) + .map((m) => m.text) + .toSet(); + expect( + slot0Texts, + containsAll({'beta history', 'live during sync'}), + reason: + 'the reload must merge with what the flush just filed, ' + 'not clobber it', + ); + }, + ); + + test( + 'outgoing send to an unconfirmed slot is refused, not orphaned', + () async { + final alpha = _channel(0, 'Alpha', 10); + final beta = _channel(1, 'Beta', 30); + c.seedCachedChannelsForTest([alpha, beta]); + + // Slot 0 confirms, slot 1 never does. + await c.getChannels(maxChannels: 2); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Alpha', pskSeed: 10), + ); + await _settle(2); + for (var i = 0; i <= 3; i++) { + c.handleChannelSyncTimeoutForTest(1); + await _settle(2); + } + await _settle(); + expect(c.unconfirmedChannelSlots, {1}); + expect(c.canSendOnChannel(0), isTrue); + expect(c.canSendOnChannel(1), isFalse); + + final sentFrames = []; + c.sendFrameOverrideForTest = sentFrames.add; + await c.sendChannelMessage(beta, 'must not be written'); + await _settle(); + + expect(sentFrames, isEmpty, reason: 'nothing may go to the radio'); + expect( + c.channelMessagesForTest[1] ?? const [], + isEmpty, + reason: + 'the refused message must not be filed (a persisted copy would ' + 'fall back to the legacy slot-index key and be orphaned)', + ); + }, + ); + + test( + 'held frames never cross radios; they flush when their radio returns', + () async { + // Radio X delivers a message before its list is confirmed; the frame is + // held. The user then connects radio Y: Y's sync must NOT flush X's frame + // into Y's conversations. When X reconnects and syncs, the frame files. + final radioX = Uint8List.fromList(List.generate(32, (i) => i)); + final radioY = Uint8List.fromList(List.generate(32, (i) => 99 + i)); + + c.handleFrameForTest( + _v3ChannelMsgFrame(channelIdx: 0, text: 'A: from X'), + ); + await _settle(); + + // Switch to radio Y and complete its sync. + c.resetConnectionHandshakeStateForTest(); + c.setConnectedForTest(); + c.setSelfPublicKeyForTest(radioY); + c.wireMessageStoreForTest(); + await syncWith([_channel(0, 'Gamma', 70)]); + expect( + c.channelMessagesForTest[0] ?? const [], + isEmpty, + reason: "radio X's held frame must not file into radio Y's channel", + ); + + // Back to radio X: its held frame now files against its own list. + c.resetConnectionHandshakeStateForTest(); + c.setConnectedForTest(); + c.setSelfPublicKeyForTest(radioX); + c.wireMessageStoreForTest(); + await syncWith([_channel(0, 'Alpha', 10)]); + expect( + (c.channelMessagesForTest[0] ?? const []).map( + (m) => m.text, + ), + ['from X'], + ); + }, + ); } diff --git a/untranslated.json b/untranslated.json index ea2bfb1d..3af74f33 100644 --- a/untranslated.json +++ b/untranslated.json @@ -159,6 +159,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -502,6 +503,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -845,6 +847,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -1188,6 +1191,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -1531,6 +1535,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -1874,6 +1879,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -2217,6 +2223,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -2560,6 +2567,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -2903,6 +2911,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -3246,6 +3255,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -3589,6 +3599,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -3932,6 +3943,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -4275,6 +4287,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -4618,6 +4631,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -4961,6 +4975,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -5304,6 +5319,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -5647,6 +5663,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames",