From 0506738925645008394e05cec0c8dcd2768a83ae Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:14:08 -0400 Subject: [PATCH 1/7] fix(#1022): stop channel adds overwriting occupied slots, including Public Adding #qcchams and #qcchhv from the phone lost Public, from the client and the radio. Three faults combined, all client-side; the firmware's CMD_SET_CHANNEL is a plain indexed write by design and did what it was told. 1. The slot was chosen when the add dialog opened (_showAddChannelDialog computed nextIndex before showDialog and closed over it), so it was stale by the time Add was pressed. 2. The connector empties its channel list for the duration of a sync and refills it slot by slot, so a dialog opened mid-sync saw every slot as free. 3. _findNextAvailableIndex answered 'no free slot' with return 0, which is where Public normally lives, turning a full radio into a silent overwrite of Public. The decision moves into a pure helper, decideChannelSlot, called at the moment of each write and never earlier. It refuses while isSyncingChannels is true and refuses when full, returning a named reason rather than slot 0. Deliberately isSyncingChannels and not hasLoadedChannels: the latter stays false after a FAILED sync while the cached list is restored into use, so gating on it would disable adding a channel permanently on a flaky link. Add Public no longer hardcodes slot 0, which it wrote with no occupancy check. Public is identified by its PSK, not its index, so it takes a free slot like any other channel, and is refused if it is already present. Owner ruling: block the unsafe write but keep the control live, since a greyed-out button is itself a silent failure. Every refusal explains itself and passes persist: true, because showDismissibleSnackBar defaults to a 4 second toast that SAFELANE 6 rules out for an error. A refused add leaves the dialog open so the user can retry. Mutation-tested rather than trusted: restoring return 0 fails 2 tests, and removing the sync guard fails 4, including the exact reported scenario. Full suite 1779 pass. New strings are English-only with the regenerated untranslated.json, matching the convention of every recent string-adding commit. Co-Authored-By: Claude Opus 5.5 --- lib/helpers/channel_slot_decision.dart | 60 ++++++ lib/l10n/app_en.arb | 10 + lib/l10n/app_localizations.dart | 18 ++ lib/l10n/app_localizations_bg.dart | 13 ++ lib/l10n/app_localizations_de.dart | 13 ++ lib/l10n/app_localizations_en.dart | 13 ++ lib/l10n/app_localizations_es.dart | 13 ++ lib/l10n/app_localizations_fr.dart | 13 ++ lib/l10n/app_localizations_hu.dart | 13 ++ lib/l10n/app_localizations_it.dart | 13 ++ lib/l10n/app_localizations_ja.dart | 13 ++ lib/l10n/app_localizations_ko.dart | 13 ++ lib/l10n/app_localizations_nl.dart | 13 ++ lib/l10n/app_localizations_pl.dart | 13 ++ lib/l10n/app_localizations_pt.dart | 13 ++ lib/l10n/app_localizations_ru.dart | 13 ++ lib/l10n/app_localizations_sk.dart | 13 ++ lib/l10n/app_localizations_sl.dart | 13 ++ lib/l10n/app_localizations_sv.dart | 13 ++ lib/l10n/app_localizations_uk.dart | 13 ++ lib/l10n/app_localizations_zh.dart | 13 ++ lib/screens/channels_screen.dart | 150 +++++++++++---- test/helpers/channel_slot_decision_test.dart | 181 +++++++++++++++++++ untranslated.json | 51 ++++++ 24 files changed, 671 insertions(+), 33 deletions(-) create mode 100644 lib/helpers/channel_slot_decision.dart create mode 100644 test/helpers/channel_slot_decision_test.dart diff --git a/lib/helpers/channel_slot_decision.dart b/lib/helpers/channel_slot_decision.dart new file mode 100644 index 00000000..5bca5ab2 --- /dev/null +++ b/lib/helpers/channel_slot_decision.dart @@ -0,0 +1,60 @@ +import '../models/channel.dart'; + +/// Why a channel slot could not be allocated. +enum ChannelSlotRefusal { + /// The channel list is mid-rewrite, so no slot can be trusted to be free. + syncing, + + /// Every slot on the radio is in use. + full, +} + +/// Either a slot that is safe to write, or the reason it was refused. +class ChannelSlotDecision { + const ChannelSlotDecision.slot(int this.slot) : refusal = null; + const ChannelSlotDecision.refused(ChannelSlotRefusal this.refusal) + : slot = null; + + final int? slot; + final ChannelSlotRefusal? refusal; + + bool get isAllowed => slot != null; +} + +/// Decide which channel slot a new channel may occupy (#1021). +/// +/// Pulled out of the channels screen so it can be tested without a widget, and +/// so the QR and config-import paths can share one answer instead of each +/// carrying their own (there were three divergent implementations, and only one +/// of them had the bug). +/// +/// Two refusals, both deliberate: +/// +/// * [isSyncing] true means the connector has emptied its channel list and is +/// refilling it slot by slot. Any index would look free. Choosing one here is +/// what overwrote Public: a slot picked during a sync pointed at an occupied +/// slot by the time it was written. +/// * No free index means the radio is full. The caller must be told, never +/// handed slot 0 as a consolation, which is the old `return 0` bug and is +/// where Public normally lives. +/// +/// Callers pass the connector's `isSyncingChannels`, not `hasLoadedChannels`: +/// the latter stays false after a *failed* sync while the cached list is +/// restored into use, so gating on it would refuse forever on a flaky link. +/// +/// An absent index genuinely means a free slot, because the connector never +/// adds an empty channel to its list. +ChannelSlotDecision decideChannelSlot({ + required List channels, + required int maxChannels, + required bool isSyncing, +}) { + if (isSyncing) { + return const ChannelSlotDecision.refused(ChannelSlotRefusal.syncing); + } + final used = channels.map((c) => c.index).toSet(); + for (var i = 0; i < maxChannels; i++) { + if (!used.contains(i)) return ChannelSlotDecision.slot(i); + } + return const ChannelSlotDecision.refused(ChannelSlotRefusal.full); +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index c9584788..b8a829e2 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1032,6 +1032,16 @@ } }, "channels_publicChannelAdded": "Public channel added", + "channels_slotBusySyncing": "Still reading channels from the radio. Try adding again in a moment.", + "channels_slotsAllFull": "All {count} channel slots are in use. Delete a channel first.", + "@channels_slotsAllFull": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "channels_publicAlreadyAdded": "The Public channel is already on this radio.", "channels_sortBy": "Sort by", "channels_sortManual": "Manual", "channels_sortAZ": "A-Z", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index ef8aa1f4..f39de2ce 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3232,6 +3232,24 @@ abstract class AppLocalizations { /// **'Public channel added'** String get channels_publicChannelAdded; + /// No description provided for @channels_slotBusySyncing. + /// + /// In en, this message translates to: + /// **'Still reading channels from the radio. Try adding again in a moment.'** + String get channels_slotBusySyncing; + + /// No description provided for @channels_slotsAllFull. + /// + /// In en, this message translates to: + /// **'All {count} channel slots are in use. Delete a channel first.'** + String channels_slotsAllFull(int count); + + /// No description provided for @channels_publicAlreadyAdded. + /// + /// In en, this message translates to: + /// **'The Public channel is already on this radio.'** + String get channels_publicAlreadyAdded; + /// No description provided for @channels_sortBy. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 90863dd3..3cfb4d48 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1833,6 +1833,19 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channels_publicChannelAdded => 'Публичен канал добавен'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Сортирай по'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 4783561f..06529dce 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1828,6 +1828,19 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_publicChannelAdded => 'Öffentlicher Kanal hinzugefügt'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Sortiere nach'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 55cc9ca7..a88a3fbf 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1806,6 +1806,19 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_publicChannelAdded => 'Public channel added'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Sort by'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 755a8e4c..ebf54667 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1829,6 +1829,19 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_publicChannelAdded => 'Canal público añadido'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Ordenar por'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 554ef261..b5df8fa4 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1834,6 +1834,19 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_publicChannelAdded => 'Le canal public a été ajouté'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Trier par'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 75dce93e..358214d7 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1834,6 +1834,19 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_publicChannelAdded => 'A nyilvános csatorna hozzáadva'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Szűrés'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index c009c111..ae0b0bf2 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1831,6 +1831,19 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_publicChannelAdded => 'Canale pubblico aggiunto'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Ordina per'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index afb53252..7d110e3a 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1772,6 +1772,19 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_publicChannelAdded => 'パブリックチャンネルが追加されました'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => '並び替え'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index bc4cdf39..5531746b 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1767,6 +1767,19 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_publicChannelAdded => '공개 채널 추가'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => '정렬 기준 선택'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 5b0d9b3b..b9ccf671 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1819,6 +1819,19 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_publicChannelAdded => 'Open kanaal toegevoegd'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Sorteren door'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index c209edc4..711c3dce 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1840,6 +1840,19 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_publicChannelAdded => 'Kanał publiczny dodany'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Sortuj po'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index f63eb395..f6c58fec 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1828,6 +1828,19 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_publicChannelAdded => 'Canal público adicionado'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Ordenar por'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index f6f00478..872d8174 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1829,6 +1829,19 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_publicChannelAdded => 'Публичный канал добавлен'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Сортировка'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 076a7d9f..da8721b1 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1820,6 +1820,19 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_publicChannelAdded => 'Veľký kanál pridaný'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Triediť podľa'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index dd594b0f..6d473d9f 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1817,6 +1817,19 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_publicChannelAdded => 'javna skupnost dodana'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Sortiraj po'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index c803fb43..4d6cfc4c 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1809,6 +1809,19 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_publicChannelAdded => 'Allmänt kanal tillagd'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Sortera efter'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index aeade4c7..e5749a0d 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1824,6 +1824,19 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_publicChannelAdded => 'Публічний канал додано'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => 'Сортувати за'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index b5f19995..a11afb1d 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1753,6 +1753,19 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_publicChannelAdded => '已添加公共频道'; + @override + String get channels_slotBusySyncing => + 'Still reading channels from the radio. Try adding again in a moment.'; + + @override + String channels_slotsAllFull(int count) { + return 'All $count channel slots are in use. Delete a channel first.'; + } + + @override + String get channels_publicAlreadyAdded => + 'The Public channel is already on this radio.'; + @override String get channels_sortBy => '排序方式'; diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 3d0e983c..74a4fb25 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -30,6 +30,7 @@ import '../widgets/channel_notify_mode.dart'; import '../widgets/radio_channel_notify.dart'; import '../widgets/radio_tone.dart'; import '../widgets/battery_optimization_banner.dart'; +import '../helpers/channel_slot_decision.dart'; import '../helpers/snack_bar_builder.dart'; import 'channel_chat_screen.dart'; import 'community_qr_scanner_screen.dart'; @@ -814,10 +815,10 @@ class _ChannelsScreenState extends State void _showAddChannelDialog(BuildContext context) { final connector = context.read(); - final nextIndex = _findNextAvailableIndex( - connector.channels, - connector.maxChannels, - ); + // No slot is chosen here. It used to be, and that was the bug: the channel + // list is emptied for the duration of a sync, so an index picked when this + // dialog opened could point at an occupied slot by the time Add was + // pressed. Each handler now calls _allocateChannelSlot at the write (#1021). final hasPublicChannel = connector.channels.any((c) => c.isPublicChannel); int? selectedOption; final nameController = TextEditingController(); @@ -920,19 +921,22 @@ class _ChannelsScreenState extends State ); return; } + final slot = _allocateChannelSlot( + dialogContext, + connector, + ); + // Refused: leave the dialog open so the user + // can retry once the sync finishes. + if (slot == null) return; final random = Random.secure(); final psk = Uint8List(16); for (int i = 0; i < 16; i++) { psk[i] = random.nextInt(256); } Navigator.pop(dialogContext); - await connector.setChannel( - nextIndex, - name, - psk, - ); + await connector.setChannel(slot, name, psk); await channelMessageStore.clearChannelMessages( - nextIndex, + slot, ); if (context.mounted) { showDismissibleSnackBar( @@ -1016,8 +1020,13 @@ class _ChannelsScreenState extends State ); return; } + final slot = _allocateChannelSlot( + dialogContext, + connector, + ); + if (slot == null) return; Navigator.pop(dialogContext); - connector.setChannel(nextIndex, name, psk); + connector.setChannel(slot, name, psk); if (context.mounted) { showDismissibleSnackBar( context, @@ -1047,11 +1056,16 @@ class _ChannelsScreenState extends State Expanded( child: FilledButton( onPressed: () { + final slot = _allocateChannelSlot( + dialogContext, + connector, + ); + if (slot == null) return; final psk = Channel.parsePskHex( Channel.publicChannelPsk, ); Navigator.pop(dialogContext); - connector.setChannel(nextIndex, 'Public', psk); + connector.setChannel(slot, 'Public', psk); if (context.mounted) { showDismissibleSnackBar( context, @@ -1229,14 +1243,19 @@ class _ChannelsScreenState extends State _loadCommunities(); } + // The screen's context, not the dialog's: the + // hashtag store write above is awaited, so the + // dialog may already be gone by here. + if (!context.mounted) return; + final slot = _allocateChannelSlot( + context, + connector, + ); + if (slot == null) return; if (dialogContext.mounted) { Navigator.pop(dialogContext); } - connector.setChannel( - nextIndex, - channelName, - psk, - ); + connector.setChannel(slot, channelName, psk); if (context.mounted) { showDismissibleSnackBar( context, @@ -1355,17 +1374,28 @@ class _ChannelsScreenState extends State // Save to store await _communityStore.addCommunity(community); - // Optionally add the community public channel to the device - if (addPublicChannel) { - final psk = community - .deriveCommunityPublicPsk(); - final channelName = - '${community.name} Public'; - connector.setChannel( - nextIndex, - channelName, - psk, + // Optionally add the community public channel to the device. + // The community itself is already saved above, + // so a refused slot skips only the channel + // write and never loses the community. Uses the + // screen's context, not the dialog's: this runs + // after an await and the dialog may be gone. + if (addPublicChannel && context.mounted) { + final slot = _allocateChannelSlot( + context, + connector, ); + if (slot != null) { + final psk = community + .deriveCommunityPublicPsk(); + final channelName = + '${community.name} Public'; + connector.setChannel( + slot, + channelName, + psk, + ); + } } if (dialogContext.mounted) { @@ -1843,20 +1873,74 @@ class _ChannelsScreenState extends State } void _addPublicChannel(BuildContext context, MeshCoreConnector connector) { + // This used to write slot 0 unconditionally, with no occupancy check, so + // it overwrote whatever was there (#1021). Public is identified by its PSK + // (`Channel.isPublicChannel`), not by its index, so it has no claim on + // slot 0 and can live anywhere. + if (connector.channels.any((c) => c.isPublicChannel)) { + _showChannelBlockedMessage( + context, + context.l10n.channels_publicAlreadyAdded, + ); + return; + } + final slot = _allocateChannelSlot(context, connector); + if (slot == null) return; final psk = Channel.parsePskHex(Channel.publicChannelPsk); - connector.setChannel(0, 'Public', psk); + connector.setChannel(slot, 'Public', psk); showDismissibleSnackBar( context, content: Text(context.l10n.channels_publicChannelAdded), ); } - int _findNextAvailableIndex(List channels, int maxChannels) { - final usedIndices = channels.map((c) => c.index).toSet(); - for (int i = 0; i < maxChannels; i++) { - if (!usedIndices.contains(i)) return i; + /// A slot that is safe to write right now, or null after explaining why not. + /// + /// Call this at the moment of the write and never earlier. The connector + /// empties `channels` for the duration of a channel sync, so a slot chosen + /// when a dialog opened can look free when it is not; that is what lost + /// Public in #1021. + /// + /// The decision itself lives in [decideChannelSlot] so it can be tested + /// without a widget and shared with the QR and config-import paths. This + /// wrapper only turns a refusal into something the user can read. + /// + /// The owner's ruling is that the unsafe write is blocked but the control + /// stays live: a greyed-out button prevents the damage and tells the user + /// nothing. So both refusals return null *and* say what is wrong. + int? _allocateChannelSlot(BuildContext context, MeshCoreConnector connector) { + final decision = decideChannelSlot( + channels: connector.channels, + maxChannels: connector.maxChannels, + // isSyncingChannels, not hasLoadedChannels: the latter stays false after + // a FAILED sync while the cached list is restored, so gating on it would + // make adding a channel impossible on a flaky link. + isSyncing: connector.isSyncingChannels, + ); + switch (decision.refusal) { + case ChannelSlotRefusal.syncing: + _showChannelBlockedMessage( + context, + context.l10n.channels_slotBusySyncing, + ); + return null; + case ChannelSlotRefusal.full: + _showChannelBlockedMessage( + context, + context.l10n.channels_slotsAllFull(connector.maxChannels), + ); + return null; + case null: + return decision.slot; } - return 0; + } + + /// A refusal the user has to be able to read and act on, so it persists. + /// + /// `showDismissibleSnackBar` defaults to `persist: false` and a 4 second + /// toast, which SAFELANE 6 rules out for an error. + void _showChannelBlockedMessage(BuildContext context, String message) { + showDismissibleSnackBar(context, content: Text(message), persist: true); } void _showManageCommunitiesDialog(BuildContext context) { diff --git a/test/helpers/channel_slot_decision_test.dart b/test/helpers/channel_slot_decision_test.dart new file mode 100644 index 00000000..a4a6dc1c --- /dev/null +++ b/test/helpers/channel_slot_decision_test.dart @@ -0,0 +1,181 @@ +// Channel slot allocation (#1021). Adding a channel could overwrite another, +// including Public, losing it from the client and the radio. +// +// Three faults combined: the slot was chosen when the add dialog opened, the +// connector empties its channel list during a sync so any index looked free, +// and the chooser answered "no free slot" with slot 0, which is where Public +// normally lives. These pin the decision so none of them can come back. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/channel_slot_decision.dart'; +import 'package:meshcore_open/models/channel.dart'; + +Channel _ch(int index, {String name = 'ch', String? pskHex}) => Channel( + index: index, + name: name, + psk: Channel.parsePskHex(pskHex ?? '00112233445566778899aabbccddeeff'), +); + +void main() { + group('decideChannelSlot', () { + test('takes the lowest free slot', () { + final d = decideChannelSlot( + channels: [_ch(0), _ch(1), _ch(3)], + maxChannels: 8, + isSyncing: false, + ); + expect(d.isAllowed, isTrue); + expect(d.slot, 2); + expect(d.refusal, isNull); + }); + + test('takes slot 0 when the radio is empty', () { + final d = decideChannelSlot( + channels: const [], + maxChannels: 8, + isSyncing: false, + ); + expect(d.slot, 0); + }); + + test('refuses with full, NEVER slot 0, when every slot is used', () { + final d = decideChannelSlot( + channels: [for (var i = 0; i < 8; i++) _ch(i)], + maxChannels: 8, + isSyncing: false, + ); + expect(d.isAllowed, isFalse); + expect(d.refusal, ChannelSlotRefusal.full); + expect( + d.slot, + isNull, + reason: 'the old return 0 fallback is what destroyed Public', + ); + }); + + test('refuses while syncing, even though every slot looks free', () { + // This is the reported bug. Mid-sync the connector has emptied its list, + // so an empty list plus a free-looking slot 0 is exactly the state that + // overwrote Public. + final d = decideChannelSlot( + channels: const [], + maxChannels: 8, + isSyncing: true, + ); + expect(d.isAllowed, isFalse); + expect(d.refusal, ChannelSlotRefusal.syncing); + expect(d.slot, isNull); + }); + + test('syncing is refused even when a slot genuinely is free', () { + final d = decideChannelSlot( + channels: [_ch(0)], + maxChannels: 8, + isSyncing: true, + ); + expect(d.refusal, ChannelSlotRefusal.syncing); + }); + + test('syncing takes precedence over full', () { + final d = decideChannelSlot( + channels: [for (var i = 0; i < 8; i++) _ch(i)], + maxChannels: 8, + isSyncing: true, + ); + expect( + d.refusal, + ChannelSlotRefusal.syncing, + reason: 'a list being rewritten cannot be trusted to say it is full', + ); + }); + + // The regression test for the gate I nearly got wrong. After a FAILED sync + // the connector leaves hasLoadedChannels false but restores the cached + // list into use. Gating on that flag would refuse forever on a flaky link, + // so the decision takes isSyncing only, and a restored list allocates + // normally. + test('allocates normally after a failed sync, from the restored list', () { + final d = decideChannelSlot( + channels: [_ch(0), _ch(1)], + maxChannels: 8, + isSyncing: false, + ); + expect( + d.isAllowed, + isTrue, + reason: 'a failed sync must not disable adding channels', + ); + expect(d.slot, 2); + }); + + test('a single-slot radio can be filled and then refuses', () { + expect( + decideChannelSlot( + channels: const [], + maxChannels: 1, + isSyncing: false, + ).slot, + 0, + ); + expect( + decideChannelSlot( + channels: [_ch(0)], + maxChannels: 1, + isSyncing: false, + ).refusal, + ChannelSlotRefusal.full, + ); + }); + + test('an out-of-range index in the list does not block a free slot', () { + // Defensive: a stale or odd index must not make the radio look full. + final d = decideChannelSlot( + channels: [_ch(99)], + maxChannels: 4, + isSyncing: false, + ); + expect(d.slot, 0); + }); + + test('Public holds no claim on slot 0, since it is identified by PSK', () { + // `Channel.isPublicChannel` compares the PSK, not the index, so Public + // can live anywhere and nothing may assume slot 0 belongs to it. + final public = Channel( + index: 3, + name: 'Public', + psk: Channel.parsePskHex(Channel.publicChannelPsk), + ); + expect(public.isPublicChannel, isTrue); + final d = decideChannelSlot( + channels: [public], + maxChannels: 8, + isSyncing: false, + ); + expect(d.slot, 0, reason: 'slot 0 is free here and may be used'); + }); + + test('a decision is either a slot or a refusal, never both', () { + final allowed = decideChannelSlot( + channels: const [], + maxChannels: 4, + isSyncing: false, + ); + final refused = decideChannelSlot( + channels: const [], + maxChannels: 4, + isSyncing: true, + ); + expect(allowed.slot != null && allowed.refusal == null, isTrue); + expect(refused.slot == null && refused.refusal != null, isTrue); + }); + }); + + group('Uint8List psk sanity', () { + test('the helper builds channels with a real 16 byte psk', () { + expect(_ch(0).psk, isA()); + expect(_ch(0).psk.length, 16); + }); + }); +} diff --git a/untranslated.json b/untranslated.json index 8a149493..1ca45ae3 100644 --- a/untranslated.json +++ b/untranslated.json @@ -154,6 +154,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -524,6 +527,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -894,6 +900,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -1264,6 +1273,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -1634,6 +1646,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2004,6 +2019,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2374,6 +2392,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2744,6 +2765,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3114,6 +3138,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3484,6 +3511,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3854,6 +3884,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -4224,6 +4257,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -4594,6 +4630,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -4964,6 +5003,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -5334,6 +5376,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -5704,6 +5749,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -6074,6 +6122,9 @@ "channels_radioSoundFollows", "channels_radioSoundMutedByRadio", "channels_radioSoundReading", + "channels_slotBusySyncing", + "channels_slotsAllFull", + "channels_publicAlreadyAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", From 9a5cd0caf763a440c9e094301506c2bb36b1a2bf Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:27:06 -0400 Subject: [PATCH 2/7] fix(#1023): every add-channel path chooses its slot at the write The channels screen was fixed in #1022, but two more surfaces chose a channel slot on their own and had the same race. Community QR scanner: - A channel share link picked its slot before the confirm dialog and wrote it after, so a sync during the confirmation (setChannel itself starts one) could leave it pointing at an occupied slot. The slot is now chosen after the user confirms, and a refusal keeps the screen open with the reason showing. - Joining a community skipped the public channel silently when the radio was full and still showed the green "joined" toast. A refusal now explains itself, and the green toast shows only when the channel was actually written. - Its private slot finder is deleted. Config import: - planChannelImport takes a required isSyncing. Mid-sync the connector's channel list is empty, so the planner would have written every incoming channel from slot 0 up, over Public. It now plans nothing and reports each channel as skipped with a new channelsSyncing reason. The parameter is required so a caller cannot forget it and get the unsafe behavior by default. Both screens now share allocateChannelSlotOrExplain (lib/helpers/channel_slot_ui.dart), so the "which slot is free" question has a single answer. channels_noFreeSlot is retired; its only caller moved to the shared message. Tests: two planner tests for the syncing case, mutation-checked (with the guard disabled both fail). Full suite 1781 pass, analyze clean. Co-Authored-By: Claude Opus 5.5 --- lib/helpers/channel_slot_ui.dart | 59 +++++++++++++++++ lib/l10n/app_en.arb | 5 +- lib/l10n/app_localizations.dart | 12 ++-- lib/l10n/app_localizations_bg.dart | 7 +- lib/l10n/app_localizations_de.dart | 7 +- lib/l10n/app_localizations_en.dart | 7 +- lib/l10n/app_localizations_es.dart | 7 +- lib/l10n/app_localizations_fr.dart | 7 +- lib/l10n/app_localizations_hu.dart | 7 +- lib/l10n/app_localizations_it.dart | 7 +- lib/l10n/app_localizations_ja.dart | 7 +- lib/l10n/app_localizations_ko.dart | 7 +- lib/l10n/app_localizations_nl.dart | 7 +- lib/l10n/app_localizations_pl.dart | 7 +- lib/l10n/app_localizations_pt.dart | 7 +- lib/l10n/app_localizations_ru.dart | 7 +- lib/l10n/app_localizations_sk.dart | 7 +- lib/l10n/app_localizations_sl.dart | 7 +- lib/l10n/app_localizations_sv.dart | 7 +- lib/l10n/app_localizations_uk.dart | 7 +- lib/l10n/app_localizations_zh.dart | 7 +- lib/screens/channels_screen.dart | 60 +++-------------- lib/screens/community_qr_scanner_screen.dart | 64 ++++++++++--------- lib/screens/import_config_screen.dart | 2 + lib/services/stock_config_import_service.dart | 19 ++++++ .../stock_config_import_service_test.dart | 44 +++++++++++++ untranslated.json | 34 +++++----- 27 files changed, 267 insertions(+), 158 deletions(-) create mode 100644 lib/helpers/channel_slot_ui.dart diff --git a/lib/helpers/channel_slot_ui.dart b/lib/helpers/channel_slot_ui.dart new file mode 100644 index 00000000..c8a7f5c0 --- /dev/null +++ b/lib/helpers/channel_slot_ui.dart @@ -0,0 +1,59 @@ +import 'package:flutter/material.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; +import 'channel_slot_decision.dart'; +import 'snack_bar_builder.dart'; + +/// A channel slot that is safe to write right now, or null after telling the +/// user why not (#1021). +/// +/// Every surface that adds a channel goes through this one function: the +/// channels screen, the community QR scanner, and anything else that writes a +/// slot. That is deliberate. The bug this fixes existed because the same +/// question ("which slot is free?") was answered three different ways in three +/// files, and only one of them was wrong. One answer cannot drift. +/// +/// Call it at the moment of the write and never earlier. The connector empties +/// its channel list for the duration of a channel sync, and `setChannel` itself +/// starts one, so a slot chosen before a dialog or a confirmation can point at +/// an occupied slot by the time it is written. +/// +/// The owner's ruling is that the unsafe write is blocked but the control stays +/// live: a greyed-out button prevents the damage and tells the user nothing. So +/// a refusal returns null *and* says what is wrong. +int? allocateChannelSlotOrExplain( + BuildContext context, + MeshCoreConnector connector, +) { + final decision = decideChannelSlot( + channels: connector.channels, + maxChannels: connector.maxChannels, + // isSyncingChannels, not hasLoadedChannels: the latter stays false after a + // FAILED sync while the cached list is restored, so gating on it would make + // adding a channel impossible on a flaky link. + isSyncing: connector.isSyncingChannels, + ); + switch (decision.refusal) { + case ChannelSlotRefusal.syncing: + showChannelBlockedMessage(context, context.l10n.channels_slotBusySyncing); + return null; + case ChannelSlotRefusal.full: + showChannelBlockedMessage( + context, + context.l10n.channels_slotsAllFull(connector.maxChannels), + ); + return null; + case null: + return decision.slot; + } +} + +/// A refusal the user has to be able to read and act on, so it persists until +/// dismissed. +/// +/// `showDismissibleSnackBar` defaults to `persist: false` and a 4 second toast, +/// which SAFELANE 6 rules out for an error. +void showChannelBlockedMessage(BuildContext context, String message) { + showDismissibleSnackBar(context, content: Text(message), persist: true); +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index b8a829e2..e7a9b862 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -2524,7 +2524,6 @@ "channels_scanQrDesc": "Add a community or channel from a QR code", "channels_scanQrInstructions": "Point at a MeshCore QR code", "channels_invalidQr": "Invalid QR code", - "channels_noFreeSlot": "No free channel slot", "channels_qrAddConfirm": "Add channel \"{name}\"?", "@channels_qrAddConfirm": { "placeholders": { @@ -3415,6 +3414,10 @@ "@importConfig_reasonNoFreeSlot": { "description": "Skip reason: every channel slot is occupied (#576)." }, + "importConfig_reasonChannelsSyncing": "channels were still being read from the radio; import again in a moment", + "@importConfig_reasonChannelsSyncing": { + "description": "Skip reason: the channel list was mid-sync, so no slot could be trusted to be free (#1021)." + }, "importConfig_reasonAbsentFromFile": "not present in this file", "@importConfig_reasonAbsentFromFile": { "description": "Failure reason: the file did not contain the section (#576)." diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index f39de2ce..5b472541 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -7514,12 +7514,6 @@ abstract class AppLocalizations { /// **'Invalid QR code'** String get channels_invalidQr; - /// No description provided for @channels_noFreeSlot. - /// - /// In en, this message translates to: - /// **'No free channel slot'** - String get channels_noFreeSlot; - /// No description provided for @channels_qrAddConfirm. /// /// In en, this message translates to: @@ -9514,6 +9508,12 @@ abstract class AppLocalizations { /// **'no free channel slot on the device'** String get importConfig_reasonNoFreeSlot; + /// Skip reason: the channel list was mid-sync, so no slot could be trusted to be free (#1021). + /// + /// In en, this message translates to: + /// **'channels were still being read from the radio; import again in a moment'** + String get importConfig_reasonChannelsSyncing; + /// Failure reason: the file did not contain the section (#576). /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 3cfb4d48..bfcd08f8 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -4423,9 +4423,6 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5652,6 +5649,10 @@ class AppLocalizationsBg extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 06529dce..4785e1c3 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -4429,9 +4429,6 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5669,6 +5666,10 @@ class AppLocalizationsDe extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index a88a3fbf..7935fcc7 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -4360,9 +4360,6 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5575,6 +5572,10 @@ class AppLocalizationsEn extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index ebf54667..4bf9f43a 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -4418,9 +4418,6 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5657,6 +5654,10 @@ class AppLocalizationsEs extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index b5df8fa4..9019475c 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -4440,9 +4440,6 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5685,6 +5682,10 @@ class AppLocalizationsFr extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 358214d7..0ed159ea 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -4435,9 +4435,6 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5674,6 +5671,10 @@ class AppLocalizationsHu extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index ae0b0bf2..38b94249 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -4423,9 +4423,6 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5662,6 +5659,10 @@ class AppLocalizationsIt extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 7d110e3a..8aa32ab0 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -4237,9 +4237,6 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5428,6 +5425,10 @@ class AppLocalizationsJa extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 5531746b..1530c103 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -4239,9 +4239,6 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5429,6 +5426,10 @@ class AppLocalizationsKo extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index b9ccf671..f98e74ec 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -4404,9 +4404,6 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5637,6 +5634,10 @@ class AppLocalizationsNl extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 711c3dce..b8010a17 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -4436,9 +4436,6 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5674,6 +5671,10 @@ class AppLocalizationsPl extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index f6c58fec..91bbe94f 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -4417,9 +4417,6 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5650,6 +5647,10 @@ class AppLocalizationsPt extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 872d8174..8ee3d742 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -4425,9 +4425,6 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5668,6 +5665,10 @@ class AppLocalizationsRu extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index da8721b1..06ad05f1 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -4404,9 +4404,6 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5634,6 +5631,10 @@ class AppLocalizationsSk extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 6d473d9f..483e1ab8 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -4399,9 +4399,6 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5632,6 +5629,10 @@ class AppLocalizationsSl extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 4d6cfc4c..172a8223 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -4379,9 +4379,6 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5607,6 +5604,10 @@ class AppLocalizationsSv extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index e5749a0d..9bff7da6 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -4421,9 +4421,6 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5669,6 +5666,10 @@ class AppLocalizationsUk extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index a11afb1d..083bcbc2 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -4142,9 +4142,6 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_invalidQr => 'Invalid QR code'; - @override - String get channels_noFreeSlot => 'No free channel slot'; - @override String channels_qrAddConfirm(String name) { return 'Add channel \"$name\"?'; @@ -5302,6 +5299,10 @@ class AppLocalizationsZh extends AppLocalizations { String get importConfig_reasonNoFreeSlot => 'no free channel slot on the device'; + @override + String get importConfig_reasonChannelsSyncing => + 'channels were still being read from the radio; import again in a moment'; + @override String get importConfig_reasonAbsentFromFile => 'not present in this file'; diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 74a4fb25..052e186f 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -30,7 +30,7 @@ import '../widgets/channel_notify_mode.dart'; import '../widgets/radio_channel_notify.dart'; import '../widgets/radio_tone.dart'; import '../widgets/battery_optimization_banner.dart'; -import '../helpers/channel_slot_decision.dart'; +import '../helpers/channel_slot_ui.dart'; import '../helpers/snack_bar_builder.dart'; import 'channel_chat_screen.dart'; import 'community_qr_scanner_screen.dart'; @@ -1878,7 +1878,7 @@ class _ChannelsScreenState extends State // (`Channel.isPublicChannel`), not by its index, so it has no claim on // slot 0 and can live anywhere. if (connector.channels.any((c) => c.isPublicChannel)) { - _showChannelBlockedMessage( + showChannelBlockedMessage( context, context.l10n.channels_publicAlreadyAdded, ); @@ -1894,54 +1894,14 @@ class _ChannelsScreenState extends State ); } - /// A slot that is safe to write right now, or null after explaining why not. - /// - /// Call this at the moment of the write and never earlier. The connector - /// empties `channels` for the duration of a channel sync, so a slot chosen - /// when a dialog opened can look free when it is not; that is what lost - /// Public in #1021. - /// - /// The decision itself lives in [decideChannelSlot] so it can be tested - /// without a widget and shared with the QR and config-import paths. This - /// wrapper only turns a refusal into something the user can read. - /// - /// The owner's ruling is that the unsafe write is blocked but the control - /// stays live: a greyed-out button prevents the damage and tells the user - /// nothing. So both refusals return null *and* say what is wrong. - int? _allocateChannelSlot(BuildContext context, MeshCoreConnector connector) { - final decision = decideChannelSlot( - channels: connector.channels, - maxChannels: connector.maxChannels, - // isSyncingChannels, not hasLoadedChannels: the latter stays false after - // a FAILED sync while the cached list is restored, so gating on it would - // make adding a channel impossible on a flaky link. - isSyncing: connector.isSyncingChannels, - ); - switch (decision.refusal) { - case ChannelSlotRefusal.syncing: - _showChannelBlockedMessage( - context, - context.l10n.channels_slotBusySyncing, - ); - return null; - case ChannelSlotRefusal.full: - _showChannelBlockedMessage( - context, - context.l10n.channels_slotsAllFull(connector.maxChannels), - ); - return null; - case null: - return decision.slot; - } - } - - /// A refusal the user has to be able to read and act on, so it persists. - /// - /// `showDismissibleSnackBar` defaults to `persist: false` and a 4 second - /// toast, which SAFELANE 6 rules out for an error. - void _showChannelBlockedMessage(BuildContext context, String message) { - showDismissibleSnackBar(context, content: Text(message), persist: true); - } + /// Thin alias for the shared allocator, kept so the five call sites in this + /// file read the same as before. The logic lives in + /// `helpers/channel_slot_ui.dart` so this screen, the QR scanner and config + /// import all answer "which slot is free?" the same way (#1021). + int? _allocateChannelSlot( + BuildContext context, + MeshCoreConnector connector, + ) => allocateChannelSlotOrExplain(context, connector); void _showManageCommunitiesDialog(BuildContext context) { showModalBottomSheet( diff --git a/lib/screens/community_qr_scanner_screen.dart b/lib/screens/community_qr_scanner_screen.dart index 289edce7..f29711c4 100644 --- a/lib/screens/community_qr_scanner_screen.dart +++ b/lib/screens/community_qr_scanner_screen.dart @@ -9,6 +9,7 @@ import '../models/community.dart'; import '../storage/community_store.dart'; import '../widgets/adaptive_app_bar_title.dart'; import '../widgets/qr_scanner_widget.dart'; +import '../helpers/channel_slot_ui.dart'; import '../helpers/snack_bar_builder.dart'; /// Screen for scanning community QR codes to join communities. @@ -224,24 +225,37 @@ class _CommunityQrScannerScreenState extends State { _communityStore.setPublicKeyHex = connector.selfPublicKeyHex; await _communityStore.addCommunity(community); - // Optionally add the community public channel to the device + // Optionally add the community public channel to the device. The + // community is already saved above, so a refused slot only skips the + // channel; it never loses the community. + // + // This used to skip the channel silently when the radio was full and then + // show a green "joined" toast, which told the user everything had worked + // when the channel had not been added (#1021). A refusal now explains + // itself, and only a real success shows the green confirmation. + var channelRefused = false; if (addPublicChannel && context.mounted) { final connector = context.read(); - final nextIndex = _findNextAvailableChannelIndex(connector); - - if (nextIndex != null) { + final slot = allocateChannelSlotOrExplain(context, connector); + if (slot == null) { + channelRefused = true; + } else { final psk = community.deriveCommunityPublicPsk(); final channelName = '${community.name} Public'; - connector.setChannel(nextIndex, channelName, psk); + connector.setChannel(slot, channelName, psk); } } if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.community_joined(community.name)), - backgroundColor: Colors.green, - ); + // The refusal message is already showing and persists; a green toast + // on top of it would contradict it. + if (!channelRefused) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.community_joined(community.name)), + backgroundColor: Colors.green, + ); + } // Return to previous screen Navigator.pop(context, community); @@ -271,17 +285,11 @@ class _CommunityQrScannerScreenState extends State { } return; } - final nextIndex = _findNextAvailableChannelIndex(connector); - if (nextIndex == null) { - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.channels_noFreeSlot), - backgroundColor: Colors.red, - ); - } - return; - } + // No slot is chosen here. It used to be, and that is the same bug the + // channels screen had: the index was picked before the confirmation + // dialog below and written after it, so a channel sync during the + // confirmation (setChannel itself starts one) could leave it pointing at + // an occupied slot. The slot is now chosen after the user confirms. if (!context.mounted) return; final confirmed = await showDialog( context: context, @@ -301,7 +309,11 @@ class _CommunityQrScannerScreenState extends State { ), ); if (confirmed == true && context.mounted) { - connector.setChannel(nextIndex, channel.name, channel.psk); + final slot = allocateChannelSlotOrExplain(context, connector); + // Refused: the persistent message explains why. Stay on this screen so + // the user can retry, rather than popping away from the explanation. + if (slot == null) return; + connector.setChannel(slot, channel.name, channel.psk); showDismissibleSnackBar( context, content: Text(context.l10n.channels_qrAdded(channel.name)), @@ -312,12 +324,4 @@ class _CommunityQrScannerScreenState extends State { Navigator.pop(context); } } - - int? _findNextAvailableChannelIndex(MeshCoreConnector connector) { - final usedIndices = connector.channels.map((c) => c.index).toSet(); - for (int i = 0; i < connector.maxChannels; i++) { - if (!usedIndices.contains(i)) return i; - } - return null; - } } diff --git a/lib/screens/import_config_screen.dart b/lib/screens/import_config_screen.dart index 5f44f8ad..27f86520 100644 --- a/lib/screens/import_config_screen.dart +++ b/lib/screens/import_config_screen.dart @@ -323,6 +323,8 @@ String _reasonText(BuildContext context, StockConfigImportIssue reason) { return l10n.importConfig_reasonAlreadyPresent; case StockConfigImportIssue.noFreeSlot: return l10n.importConfig_reasonNoFreeSlot; + case StockConfigImportIssue.channelsSyncing: + return l10n.importConfig_reasonChannelsSyncing; case StockConfigImportIssue.notWritable: return l10n.importConfig_reasonNotWritable; } diff --git a/lib/services/stock_config_import_service.dart b/lib/services/stock_config_import_service.dart index 9f2db4a2..7c068042 100644 --- a/lib/services/stock_config_import_service.dart +++ b/lib/services/stock_config_import_service.dart @@ -47,6 +47,10 @@ enum StockConfigImportIssue { /// Every channel slot on the device is occupied. noFreeSlot, + /// The channel list was being re-read from the radio, so no slot could be + /// trusted to be free. Importing again once it finishes will work (#1021). + channelsSyncing, + /// We have no supported way to write this value to the device. notWritable, } @@ -274,6 +278,7 @@ class StockConfigImportService { existing: _connector.channels, incoming: incoming, maxChannels: _connector.maxChannels, + isSyncing: _connector.isSyncingChannels, ); for (final assignment in plan.assignments) { await _connector.setChannel( @@ -357,11 +362,25 @@ class ChannelImportPlan { /// New channels go into the lowest free slot. Stock's file has no index field, /// so incoming order is the only ordering information there is, and slots /// already occupied are left alone. +/// +/// While [isSyncing] is true nothing is planned. The connector empties its +/// channel list for the duration of a sync, so [existing] would look empty and +/// every incoming channel would be written over slots that are in fact +/// occupied, Public included (#1021). Each channel is reported as skipped +/// instead, so the user sees why and can import again. [isSyncing] is required +/// so a caller cannot forget it and get the unsafe behavior by default. ChannelImportPlan planChannelImport({ required List existing, required List incoming, required int maxChannels, + required bool isSyncing, }) { + if (isSyncing) { + return ChannelImportPlan(const [], [ + for (final channel in incoming) + SkippedChannel(channel.name, StockConfigImportIssue.channelsSyncing), + ]); + } final live = existing.where((c) => !c.isEmpty).toList(); final takenSlots = live.map((c) => c.index).toSet(); final psks = live.map((c) => c.pskHex).toSet(); diff --git a/test/services/stock_config_import_service_test.dart b/test/services/stock_config_import_service_test.dart index a8bcfcc1..fbafbe76 100644 --- a/test/services/stock_config_import_service_test.dart +++ b/test/services/stock_config_import_service_test.dart @@ -28,6 +28,7 @@ void main() { existing: [live(0, 'Public', 0x11)], incoming: [incoming('Weather', 0x22)], maxChannels: 40, + isSyncing: false, ); expect(plan.assignments, hasLength(1)); @@ -41,6 +42,7 @@ void main() { existing: [live(0, 'Public', 0x11)], incoming: [incoming('Renamed', 0x11)], maxChannels: 40, + isSyncing: false, ); expect(plan.assignments, isEmpty); @@ -55,6 +57,7 @@ void main() { existing: [live(0, 'Public', 0x11)], incoming: [incoming('Public', 0x99)], maxChannels: 40, + isSyncing: false, ); expect(plan.assignments, isEmpty); @@ -72,6 +75,7 @@ void main() { ], incoming: [incoming('Emergency', 0x33)], maxChannels: 40, + isSyncing: false, ); expect(plan.assignments.single.slot, 1); @@ -86,6 +90,7 @@ void main() { incoming('Third', 0x44), ], maxChannels: 40, + isSyncing: false, ); expect(plan.assignments.map((a) => a.slot), [1, 2, 3]); @@ -101,6 +106,7 @@ void main() { existing: [live(0, 'A', 0x11), live(1, 'B', 0x22)], incoming: [incoming('C', 0x33), incoming('D', 0x44)], maxChannels: 2, + isSyncing: false, ); expect(plan.assignments, isEmpty); @@ -116,6 +122,7 @@ void main() { existing: const [], incoming: [incoming('Dupe', 0x55), incoming('Dupe', 0x55)], maxChannels: 40, + isSyncing: false, ); expect(plan.assignments, hasLength(1)); @@ -127,11 +134,48 @@ void main() { existing: [live(0, 'Public', 0x11)], incoming: const [], maxChannels: 40, + isSyncing: false, ); expect(plan.assignments, isEmpty); expect(plan.skipped, isEmpty); }); + + // #1021: the connector empties its channel list for the length of a sync, + // so mid-sync `existing` looks empty. Planning then would write every + // incoming channel over slots that are really occupied, starting at 0. + test('mid-sync nothing is written, even into slots that look free', () { + final plan = planChannelImport( + existing: const [], + incoming: [incoming('Weather', 0x22), incoming('Emergency', 0x33)], + maxChannels: 40, + isSyncing: true, + ); + + expect(plan.assignments, isEmpty); + expect(plan.skipped.map((s) => s.name), ['Weather', 'Emergency']); + expect( + plan.skipped.map((s) => s.reason), + everyElement(StockConfigImportIssue.channelsSyncing), + ); + }); + + test('mid-sync every channel is reported as syncing, not as present', () { + // A partial list cannot prove a channel is already there either, so + // "already present" would be a guess. Syncing is the true reason. + final plan = planChannelImport( + existing: [live(0, 'Public', 0x11)], + incoming: [incoming('Public', 0x11)], + maxChannels: 40, + isSyncing: true, + ); + + expect(plan.assignments, isEmpty); + expect( + plan.skipped.single.reason, + StockConfigImportIssue.channelsSyncing, + ); + }); }); group('import result', () { diff --git a/untranslated.json b/untranslated.json index 1ca45ae3..4bb2074f 100644 --- a/untranslated.json +++ b/untranslated.json @@ -213,7 +213,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -321,6 +320,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -586,7 +586,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -694,6 +693,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -959,7 +959,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -1067,6 +1066,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -1332,7 +1332,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -1440,6 +1439,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -1705,7 +1705,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -1813,6 +1812,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -2078,7 +2078,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -2186,6 +2185,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -2451,7 +2451,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -2559,6 +2558,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -2824,7 +2824,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -2932,6 +2931,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -3197,7 +3197,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -3305,6 +3304,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -3570,7 +3570,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -3678,6 +3677,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -3943,7 +3943,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -4051,6 +4050,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -4316,7 +4316,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -4424,6 +4423,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -4689,7 +4689,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -4797,6 +4796,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -5062,7 +5062,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -5170,6 +5169,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -5435,7 +5435,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -5543,6 +5542,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -5808,7 +5808,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -5916,6 +5915,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", @@ -6181,7 +6181,6 @@ "channels_scanQrDesc", "channels_scanQrInstructions", "channels_invalidQr", - "channels_noFreeSlot", "channels_qrAddConfirm", "channels_qrAdded", "channels_qrExists", @@ -6289,6 +6288,7 @@ "importConfig_resultFailedHeading", "importConfig_reasonAlreadyPresent", "importConfig_reasonNoFreeSlot", + "importConfig_reasonChannelsSyncing", "importConfig_reasonAbsentFromFile", "importConfig_reasonNoReply", "importConfig_reasonUnsupported", From c8de4203f7493090936d48662aede4cc1e9351ed Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:46:40 -0400 Subject: [PATCH 3/7] fix(#1026): wait for the radio's reply before a channel write counts setChannel sent CMD_SET_CHANNEL and moved on without the radio's OK or ERR, then cleared the slot's message history on the strength of having sent it. Firmware with OffbandMesh/meshcore-firmware#1864 refuses a different channel over an occupied slot with ERR_CODE_BAD_STATE and keeps that channel intact, so the client would have deleted the history of a channel the radio still holds. Connector: - setChannel, deleteChannel and the new editChannel wait for the reply, using the existing generic-ack queue (each pending entry can now carry a completer), and return ChannelWrite: ok, occupied (BAD_STATE), rejected, or noReply (timeout, send failure, or not connected). - History is cleared only after an OK. A refusal or no reply keeps it. - A timed-out waiter leaves the queue, so a late or lost reply cannot be matched to the next command. - isChannelTableBusy covers an unanswered write as well as a sync. Without that, a second add made while the first is waiting would pick the same slot, because the list does not show the first one yet. - editChannel does clear-then-add for a new key. #1864 firmware refuses a new key written in place (owner ruling on that epic: changing a key is clear-then-add), so the edit dialog would have broken once it shipped. A rename is still a single write. Callers: - Every add, edit and delete path waits for the result and shows its success toast only after an OK; otherwise a persistent message says what happened. The two places the channels screen cleared history itself now do it only after an OK. - Edit and delete refuse, with the busy message, while the table is busy. - Config import and community delete write one channel at a time and re-read the list once at the end. A re-read after each write would put the next write inside a sync, where its reply cannot be told from the sync's. Import counts only confirmed channels; refused ones are listed as skipped. - Creating a community: the dialog closes before the write, so the wait cannot invite a second tap, and a refused channel's message is no longer replaced by the "created" toast (a #1022 regression, since a newer toast replaces the visible one). Tests: 12 connector tests driving synthetic OK / BAD_STATE / NOT_FOUND / no reply. Mutation-checked: clearing before the reply fails 3, a new key written in place fails 1, and a timed-out waiter left queued fails 1. Full suite 1793 pass, analyze clean. The refusal path cannot be exercised on a real radio until #1864 ships; the OK path can be tested on hardware now. Co-Authored-By: Claude Opus 5.5 --- lib/connector/meshcore_connector.dart | 310 ++++++++++++++---- lib/connector/meshcore_protocol.dart | 5 + lib/helpers/channel_slot_decision.dart | 7 +- lib/helpers/channel_slot_ui.dart | 42 ++- lib/l10n/app_en.arb | 14 +- lib/l10n/app_localizations.dart | 20 +- lib/l10n/app_localizations_bg.dart | 14 +- lib/l10n/app_localizations_de.dart | 14 +- lib/l10n/app_localizations_en.dart | 14 +- lib/l10n/app_localizations_es.dart | 14 +- lib/l10n/app_localizations_fr.dart | 14 +- lib/l10n/app_localizations_hu.dart | 14 +- lib/l10n/app_localizations_it.dart | 14 +- lib/l10n/app_localizations_ja.dart | 14 +- lib/l10n/app_localizations_ko.dart | 14 +- lib/l10n/app_localizations_nl.dart | 14 +- lib/l10n/app_localizations_pl.dart | 14 +- lib/l10n/app_localizations_pt.dart | 14 +- lib/l10n/app_localizations_ru.dart | 14 +- lib/l10n/app_localizations_sk.dart | 14 +- lib/l10n/app_localizations_sl.dart | 14 +- lib/l10n/app_localizations_sv.dart | 14 +- lib/l10n/app_localizations_uk.dart | 14 +- lib/l10n/app_localizations_zh.dart | 14 +- lib/screens/channels_screen.dart | 234 +++++++++---- lib/screens/community_qr_scanner_screen.dart | 21 +- lib/services/stock_config_import_service.dart | 36 +- test/connector/channel_write_reply_test.dart | 209 ++++++++++++ untranslated.json | 51 +++ 29 files changed, 1038 insertions(+), 163 deletions(-) create mode 100644 test/connector/channel_write_reply_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index d55b43cd..081eadde 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -212,6 +212,25 @@ enum IdentityTransfer { noReply, } +/// How a channel write (`CMD_SET_CHANNEL`) ended, as the radio reported it. +/// (#1026) +enum ChannelWrite { + /// The radio answered OK. + ok, + + /// The radio refused because a different channel holds the slot + /// (`ERR_CODE_BAD_STATE`, OffbandMesh/meshcore-firmware#1864). That channel + /// is still there, intact. + occupied, + + /// The radio refused for another reason, e.g. a slot index it does not have. + rejected, + + /// Not connected, or no reply before the timeout. The write may or may not + /// have landed. + noReply, +} + /// Result of [MeshCoreConnector.exportPrivateKey]. [identity] is /// non-null only when [outcome] is [IdentityTransfer.ok]. (#578) class IdentityExportResult { @@ -7231,32 +7250,17 @@ class MeshCoreConnector extends ChangeNotifier { } } - Future setChannel(int index, String name, Uint8List psk) async { - if (!isConnected) return; - - // 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); + /// How long a channel write waits for the radio's OK or ERR. (#1026) + @visibleForTesting + Duration channelWriteReplyTimeout = const Duration(seconds: 5); - await sendFrame(buildSetChannelFrame(index, name, psk)); + int _channelWritesInFlight = 0; - if (!sameChannel) { - await _channelMessageStore.clearLegacySlotHistory(index); - _channelMessages.remove(index); - } - - // Refresh channels after setting - await getChannels(force: true); - } + /// True while the channel list cannot be trusted to show which slots are + /// free: a sync is re-reading it, or a write has not been answered yet. A + /// slot chosen against it could already be taken. (#1021, #1026) + bool get isChannelTableBusy => + _isSyncingChannels || _channelWritesInFlight > 0; /// Writes the client's cached channel list back onto the radio (#1060). /// @@ -7282,47 +7286,222 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'ChannelSync', ); - var sent = 0; - for (final channel in toRestore) { - if (!isConnected) break; - await sendFrame( - buildSetChannelFrame(channel.index, channel.name, channel.psk), + // Counted as a write in flight for its whole length, so an add made while + // it runs is refused instead of choosing a slot this is about to fill + // (#1021, #1026). + _channelWritesInFlight++; + try { + var sent = 0; + for (final channel in toRestore) { + if (!isConnected) break; + await sendFrame( + buildSetChannelFrame(channel.index, channel.name, channel.psk), + ); + sent++; + // Space the writes. On BLE [sendFrame] prefers write-without-response, + // which returns once the frame reaches the OS and not once the radio + // has taken it, so an unpaced loop can overrun the radio and lose + // channels with no error anywhere. The USB branch of [sendFrame] + // already spaces its own frames for exactly this reason; BLE has no + // such pause. + if (sent < toRestore.length) { + await Future.delayed(_channelRestoreFrameGap); + } + } + + // The radio now holds these again, so a fresh sync should confirm them + // and the erased-slot block clears itself on the next pass. + // + // This deliberately does NOT report how many the radio confirmed: + // [getChannels] returns once the first request is away, not once the + // sync has finished, so counting confirmations here would read a list + // the radio has not answered for yet and report 0 every time. The + // authoritative feedback is the erased-slot banner, which is re-derived + // on every sync and therefore stays up if some writes did not land. + await getChannels(force: true); + return sent; + } finally { + _channelWritesInFlight--; + } + } + + /// Writes [name] and [psk] into slot [index] and reports what the radio said. + /// + /// [refresh] re-reads the channel list afterwards. A caller writing several + /// channels passes false and refreshes once at the end, because a write sent + /// during a sync cannot tell its reply from the sync's. + Future setChannel( + int index, + String name, + Uint8List psk, { + bool refresh = true, + }) async { + if (!isConnected) return ChannelWrite.noReply; + return _setChannel( + index, + name, + psk, + occupantPsk: _findChannelByIndex(index)?.psk, + refresh: refresh, + ); + } + + /// Writes an edit of [channel]. A rename keeps the key and is a plain write. + /// A new key is clear-then-add: firmware with + /// OffbandMesh/meshcore-firmware#1864 refuses a different channel over an + /// occupied slot, and that is what a new key in place is. + /// + /// A new key is a slot reassignment for history purposes, the same as + /// before the clear-then-add: the old key's PSK-keyed history is kept, so + /// it comes back if that key is ever re-added (#1063). + Future editChannel( + Channel channel, + String name, + Uint8List psk, + ) async { + if (!isConnected) return ChannelWrite.noReply; + if (listEquals(channel.psk, psk)) { + return _setChannel( + channel.index, + name, + psk, + occupantPsk: channel.psk, + refresh: true, ); - sent++; - // Space the writes. On BLE [sendFrame] prefers write-without-response, - // which returns once the frame reaches the OS and not once the radio has - // taken it, so an unpaced loop can overrun the radio and lose channels - // with no error anywhere. The USB branch of [sendFrame] already spaces - // its own frames for exactly this reason; BLE has no such pause. - if (sent < toRestore.length) { - await Future.delayed(_channelRestoreFrameGap); + } + _channelWritesInFlight++; + try { + final cleared = await _writeChannelSlot(channel.index, '', Uint8List(16)); + if (cleared != ChannelWrite.ok) { + await getChannels(force: true); + return cleared; } + await _retireSlotOccupant(channel.index); + return await _setChannel( + channel.index, + name, + psk, + occupantPsk: null, + refresh: true, + ); + } finally { + _channelWritesInFlight--; } + } - // The radio now holds these again, so a fresh sync should confirm them and - // the erased-slot block clears itself on the next pass. - // - // This deliberately does NOT report how many the radio confirmed: - // [getChannels] returns once the first request is away, not once the sync - // has finished, so counting confirmations here would read a list the radio - // has not answered for yet and report 0 every time. The authoritative - // feedback is the erased-slot banner, which is re-derived on every sync and - // therefore stays up if some writes did not land. - await getChannels(force: true); - return sent; + Future deleteChannel(int index, {bool refresh = true}) async { + if (!isConnected) return ChannelWrite.noReply; + _channelWritesInFlight++; + try { + // A slot is deleted by writing an empty name and a zero PSK. Its history + // goes outright (the true-delete path, #1063), once the radio has said + // OK: a refused delete leaves the channel, and it keeps its history. + final result = await _writeChannelSlot(index, '', Uint8List(16)); + if (result == ChannelWrite.ok) { + await _channelMessageStore.clearChannelMessages(index); + _channelMessages.remove(index); + } + if (refresh) await getChannels(force: true); + return result; + } finally { + _channelWritesInFlight--; + } } - Future deleteChannel(int index) async { - if (!isConnected) return; + Future _setChannel( + int index, + String name, + Uint8List psk, { + required Uint8List? occupantPsk, + required bool refresh, + }) async { + _channelWritesInFlight++; + try { + // A rename (same PSK) keeps everything; a different PSK retires the + // slot's previous occupant (see [_retireSlotOccupant]). + final sameChannel = occupantPsk != null && listEquals(occupantPsk, psk); + + final result = await _writeChannelSlot(index, name, psk); + + // Only after the radio says OK. A refused write leaves the slot's + // channel in place, and its slot-keyed state has to stay with it. (#1026) + if (result == ChannelWrite.ok && !sameChannel) { + await _retireSlotOccupant(index); + } + + // Re-read on every outcome: after a refusal the list we chose the slot + // from was wrong, and after no reply nobody knows what the slot holds. + if (refresh) await getChannels(force: true); + return result; + } finally { + _channelWritesInFlight--; + } + } + + /// Sends one `CMD_SET_CHANNEL` and waits for the radio's OK or ERR, using + /// the generic-ack queue the channel-message sends already use. + /// + /// That queue matches replies to commands by order, which holds because the + /// firmware answers commands one at a time in the order they arrive. + Future _writeChannelSlot( + int index, + String name, + Uint8List psk, + ) async { + if (!isConnected) return ChannelWrite.noReply; + final reply = Completer(); + final pending = _PendingCommandAck( + commandCode: cmdSetChannel, + reply: reply, + ); + // Queued before the frame goes out, so a fast reply cannot arrive first. + _pendingGenericAckQueue.add(pending); + try { + await sendFrame(buildSetChannelFrame(index, name, psk)); + } catch (e) { + _pendingGenericAckQueue.remove(pending); + _appDebugLogService?.error( + 'Channel write to slot $index was not sent: $e', + tag: 'ChannelWrite', + ); + return ChannelWrite.noReply; + } + final int? errCode; + try { + errCode = await reply.future.timeout(channelWriteReplyTimeout); + } on TimeoutException { + // Dropped so a late or lost reply cannot be matched to the next command. + _pendingGenericAckQueue.remove(pending); + _appDebugLogService?.warn( + 'Radio did not answer the channel write to slot $index', + tag: 'ChannelWrite', + ); + return ChannelWrite.noReply; + } + if (errCode == null) return ChannelWrite.ok; + _appDebugLogService?.warn( + 'Radio refused the channel write to slot $index (error $errCode)', + tag: 'ChannelWrite', + ); + return errCode == errCodeBadState + ? ChannelWrite.occupied + : ChannelWrite.rejected; + } - // Delete by setting empty name and zero PSK - await sendFrame(buildSetChannelFrame(index, '', Uint8List(16))); - // Clear stored messages for this channel - await _channelMessageStore.clearChannelMessages(index); - // Clear in-memory messages for this channel + /// Drops the slot-keyed remnants of a slot's previous occupant once the slot + /// has been given to a different channel. + /// + /// 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: + /// - 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). + Future _retireSlotOccupant(int index) async { + await _channelMessageStore.clearLegacySlotHistory(index); _channelMessages.remove(index); - // Refresh channels after deleting - await getChannels(force: true); } // --- Offband GPS query (CMD_OFFBAND_GPS / RESP_CODE_OFFBAND_GPS = 0xC1) (#135) @@ -8538,6 +8717,7 @@ class MeshCoreConnector extends ChangeNotifier { } final failedAck = _pendingGenericAckQueue.removeAt(0); + failedAck.answer(errCode); if (failedAck.commandCode != cmdSendChannelTxtMsg || failedAck.channelSendQueueId == null) { return; @@ -10518,6 +10698,7 @@ class MeshCoreConnector extends ChangeNotifier { } final pendingAck = _pendingGenericAckQueue.removeAt(0); + pendingAck.answer(null); if (pendingAck.commandCode != cmdSendChannelTxtMsg || pendingAck.channelSendQueueId == null) { return; @@ -12096,7 +12277,20 @@ class _PendingCommandAck { final int commandCode; final String? channelSendQueueId; - _PendingCommandAck({required this.commandCode, this.channelSendQueueId}); + /// Completed with null for OK or with the error code for ERR, for a caller + /// that waits on the reply. (#1026) + final Completer? reply; + + _PendingCommandAck({ + required this.commandCode, + this.channelSendQueueId, + this.reply, + }); + + void answer(int? errCode) { + final waiter = reply; + if (waiter != null && !waiter.isCompleted) waiter.complete(errCode); + } } /// A `0xC5` request waiting for its reply. diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index f27a9aa9..937dd9a8 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -502,6 +502,11 @@ const int errCodeUnsupportedCmd = 1; /// not hold. (#762) const int errCodeNotFound = 2; +/// `ERR_CODE_BAD_STATE`: e.g. `CMD_SET_CHANNEL` putting a different channel +/// over an occupied slot, which firmware with OffbandMesh/meshcore-firmware#1864 +/// refuses. (#1026) +const int errCodeBadState = 4; + Uint8List buildOffbandBlockAddFrame(Uint8List pubKey) => Uint8List.fromList([cmdOffbandBlock, offbandBlockAdd, ...pubKey]); Uint8List buildOffbandBlockRemoveFrame(Uint8List pubKey) => diff --git a/lib/helpers/channel_slot_decision.dart b/lib/helpers/channel_slot_decision.dart index 5bca5ab2..ee481a15 100644 --- a/lib/helpers/channel_slot_decision.dart +++ b/lib/helpers/channel_slot_decision.dart @@ -38,9 +38,10 @@ class ChannelSlotDecision { /// handed slot 0 as a consolation, which is the old `return 0` bug and is /// where Public normally lives. /// -/// Callers pass the connector's `isSyncingChannels`, not `hasLoadedChannels`: -/// the latter stays false after a *failed* sync while the cached list is -/// restored into use, so gating on it would refuse forever on a flaky link. +/// Callers pass the connector's `isChannelTableBusy` (a sync, or a write the +/// radio has not answered yet), not `hasLoadedChannels`: the latter stays false +/// after a *failed* sync while the cached list is restored into use, so gating +/// on it would refuse forever on a flaky link. /// /// An absent index genuinely means a free slot, because the connector never /// adds an empty channel to its list. diff --git a/lib/helpers/channel_slot_ui.dart b/lib/helpers/channel_slot_ui.dart index c8a7f5c0..95a6e702 100644 --- a/lib/helpers/channel_slot_ui.dart +++ b/lib/helpers/channel_slot_ui.dart @@ -29,10 +29,11 @@ int? allocateChannelSlotOrExplain( final decision = decideChannelSlot( channels: connector.channels, maxChannels: connector.maxChannels, - // isSyncingChannels, not hasLoadedChannels: the latter stays false after a - // FAILED sync while the cached list is restored, so gating on it would make - // adding a channel impossible on a flaky link. - isSyncing: connector.isSyncingChannels, + // Not hasLoadedChannels: that stays false after a FAILED sync while the + // cached list is restored, so gating on it would make adding a channel + // impossible on a flaky link. Busy also covers a write the radio has not + // answered yet (#1026): until it does, the list does not show its slot. + isSyncing: connector.isChannelTableBusy, ); switch (decision.refusal) { case ChannelSlotRefusal.syncing: @@ -57,3 +58,36 @@ int? allocateChannelSlotOrExplain( void showChannelBlockedMessage(BuildContext context, String message) { showDismissibleSnackBar(context, content: Text(message), persist: true); } + +/// Explains a channel write the radio did not confirm, and returns true if it +/// did. A caller shows its own success message only when this returns false, +/// so nothing claims success before the radio has said OK (#1026). +/// +/// A success toast shown after this would replace the explanation (a newer +/// toast replaces the visible one), so callers must not show one. +bool explainUnconfirmedChannelWrite(BuildContext context, ChannelWrite result) { + final l10n = context.l10n; + final message = switch (result) { + ChannelWrite.ok => null, + ChannelWrite.occupied => l10n.channels_writeOccupied, + ChannelWrite.rejected => l10n.channels_writeRejected, + ChannelWrite.noReply => l10n.channels_writeNoReply, + }; + if (message == null) return false; + showChannelBlockedMessage(context, message); + return true; +} + +/// For an edit or delete: refuses while the channel list is being re-read or +/// a write is unanswered, and says so. Returns true if it refused. +/// +/// Replies are matched to commands by order, so a write sent during a sync +/// could take one of the sync's replies as its own. +bool refuseWhileChannelTableBusy( + BuildContext context, + MeshCoreConnector connector, +) { + if (!connector.isChannelTableBusy) return false; + showChannelBlockedMessage(context, context.l10n.channels_slotBusySyncing); + return true; +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e7a9b862..4b1c14bc 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1032,7 +1032,7 @@ } }, "channels_publicChannelAdded": "Public channel added", - "channels_slotBusySyncing": "Still reading channels from the radio. Try adding again in a moment.", + "channels_slotBusySyncing": "The radio is still updating its channel list. Try again in a moment.", "channels_slotsAllFull": "All {count} channel slots are in use. Delete a channel first.", "@channels_slotsAllFull": { "placeholders": { @@ -1042,6 +1042,18 @@ } }, "channels_publicAlreadyAdded": "The Public channel is already on this radio.", + "channels_writeOccupied": "The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.", + "@channels_writeOccupied": { + "description": "The radio refused a channel write because a different channel holds the slot (ERR_CODE_BAD_STATE, firmware #1864). Persistent (#1026)." + }, + "channels_writeRejected": "The radio refused the change, so the channel is as it was.", + "@channels_writeRejected": { + "description": "The radio answered a channel write with an error other than slot-occupied. Persistent (#1026)." + }, + "channels_writeNoReply": "The radio did not confirm the change. Check the channel list before trying again.", + "@channels_writeNoReply": { + "description": "A channel write got no reply before the timeout, or the radio is not connected; it may or may not have landed. Persistent (#1026)." + }, "channels_sortBy": "Sort by", "channels_sortManual": "Manual", "channels_sortAZ": "A-Z", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 5b472541..90811d09 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3235,7 +3235,7 @@ abstract class AppLocalizations { /// No description provided for @channels_slotBusySyncing. /// /// In en, this message translates to: - /// **'Still reading channels from the radio. Try adding again in a moment.'** + /// **'The radio is still updating its channel list. Try again in a moment.'** String get channels_slotBusySyncing; /// No description provided for @channels_slotsAllFull. @@ -3250,6 +3250,24 @@ abstract class AppLocalizations { /// **'The Public channel is already on this radio.'** String get channels_publicAlreadyAdded; + /// The radio refused a channel write because a different channel holds the slot (ERR_CODE_BAD_STATE, firmware #1864). Persistent (#1026). + /// + /// In en, this message translates to: + /// **'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'** + String get channels_writeOccupied; + + /// The radio answered a channel write with an error other than slot-occupied. Persistent (#1026). + /// + /// In en, this message translates to: + /// **'The radio refused the change, so the channel is as it was.'** + String get channels_writeRejected; + + /// A channel write got no reply before the timeout, or the radio is not connected; it may or may not have landed. Persistent (#1026). + /// + /// In en, this message translates to: + /// **'The radio did not confirm the change. Check the channel list before trying again.'** + String get channels_writeNoReply; + /// No description provided for @channels_sortBy. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index bfcd08f8..68e444e6 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1835,7 +1835,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1846,6 +1846,18 @@ class AppLocalizationsBg extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Сортирай по'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 4785e1c3..2c8880f5 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1830,7 +1830,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1841,6 +1841,18 @@ class AppLocalizationsDe extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Sortiere nach'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 7935fcc7..dd9adba4 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1808,7 +1808,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1819,6 +1819,18 @@ class AppLocalizationsEn extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Sort by'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 4bf9f43a..e1b42311 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1831,7 +1831,7 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1842,6 +1842,18 @@ class AppLocalizationsEs extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Ordenar por'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 9019475c..3891d61d 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1836,7 +1836,7 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1847,6 +1847,18 @@ class AppLocalizationsFr extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Trier par'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 0ed159ea..d8f57f14 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1836,7 +1836,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1847,6 +1847,18 @@ class AppLocalizationsHu extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Szűrés'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 38b94249..29257893 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1833,7 +1833,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1844,6 +1844,18 @@ class AppLocalizationsIt extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Ordina per'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 8aa32ab0..f091f2a6 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1774,7 +1774,7 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1785,6 +1785,18 @@ class AppLocalizationsJa extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => '並び替え'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 1530c103..b967e75d 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1769,7 +1769,7 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1780,6 +1780,18 @@ class AppLocalizationsKo extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => '정렬 기준 선택'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index f98e74ec..aa9c204f 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1821,7 +1821,7 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1832,6 +1832,18 @@ class AppLocalizationsNl extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Sorteren door'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index b8010a17..ea1fedc1 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1842,7 +1842,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1853,6 +1853,18 @@ class AppLocalizationsPl extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Sortuj po'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 91bbe94f..382ae0a5 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1830,7 +1830,7 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1841,6 +1841,18 @@ class AppLocalizationsPt extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Ordenar por'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 8ee3d742..3bc353bf 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1831,7 +1831,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1842,6 +1842,18 @@ class AppLocalizationsRu extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Сортировка'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 06ad05f1..0ee32439 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1822,7 +1822,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1833,6 +1833,18 @@ class AppLocalizationsSk extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Triediť podľa'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 483e1ab8..b1c21333 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1819,7 +1819,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1830,6 +1830,18 @@ class AppLocalizationsSl extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Sortiraj po'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 172a8223..054e1c97 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1811,7 +1811,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1822,6 +1822,18 @@ class AppLocalizationsSv extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Sortera efter'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 9bff7da6..23dd9a56 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1826,7 +1826,7 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1837,6 +1837,18 @@ class AppLocalizationsUk extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => 'Сортувати за'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 083bcbc2..3d470f89 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1755,7 +1755,7 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_slotBusySyncing => - 'Still reading channels from the radio. Try adding again in a moment.'; + 'The radio is still updating its channel list. Try again in a moment.'; @override String channels_slotsAllFull(int count) { @@ -1766,6 +1766,18 @@ class AppLocalizationsZh extends AppLocalizations { String get channels_publicAlreadyAdded => 'The Public channel is already on this radio.'; + @override + String get channels_writeOccupied => + 'The radio refused: another channel already uses that slot, and it was left unchanged. Try again now that the list has been re-read.'; + + @override + String get channels_writeRejected => + 'The radio refused the change, so the channel is as it was.'; + + @override + String get channels_writeNoReply => + 'The radio did not confirm the change. Check the channel list before trying again.'; + @override String get channels_sortBy => '排序方式'; diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 052e186f..484f1983 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -934,18 +934,31 @@ class _ChannelsScreenState extends State psk[i] = random.nextInt(256); } Navigator.pop(dialogContext); - await connector.setChannel(slot, name, psk); - await channelMessageStore.clearChannelMessages( + final result = await connector.setChannel( slot, + name, + psk, ); - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.channels_channelAdded(name), - ), - ); + // Only on OK: a refused write leaves another + // channel in this slot, and this would wipe + // that channel's history (#1026). + if (result == ChannelWrite.ok) { + await channelMessageStore + .clearChannelMessages(slot); } + if (!context.mounted) return; + if (explainUnconfirmedChannelWrite( + context, + result, + )) { + return; + } + showDismissibleSnackBar( + context, + content: Text( + context.l10n.channels_channelAdded(name), + ), + ); }, child: Text(dialogContext.l10n.common_create), ), @@ -992,7 +1005,7 @@ class _ChannelsScreenState extends State children: [ Expanded( child: FilledButton( - onPressed: () { + onPressed: () async { final name = nameController.text.trim(); final pskHex = pskController.text.trim(); if (name.isEmpty) { @@ -1026,15 +1039,24 @@ class _ChannelsScreenState extends State ); if (slot == null) return; Navigator.pop(dialogContext); - connector.setChannel(slot, name, psk); - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.channels_channelAdded(name), - ), - ); + final result = await connector.setChannel( + slot, + name, + psk, + ); + if (!context.mounted) return; + if (explainUnconfirmedChannelWrite( + context, + result, + )) { + return; } + showDismissibleSnackBar( + context, + content: Text( + context.l10n.channels_channelAdded(name), + ), + ); }, child: Text(dialogContext.l10n.common_add), ), @@ -1055,7 +1077,7 @@ class _ChannelsScreenState extends State children: [ Expanded( child: FilledButton( - onPressed: () { + onPressed: () async { final slot = _allocateChannelSlot( dialogContext, connector, @@ -1065,15 +1087,24 @@ class _ChannelsScreenState extends State Channel.publicChannelPsk, ); Navigator.pop(dialogContext); - connector.setChannel(slot, 'Public', psk); - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.channels_publicChannelAdded, - ), - ); + final result = await connector.setChannel( + slot, + 'Public', + psk, + ); + if (!context.mounted) return; + if (explainUnconfirmedChannelWrite( + context, + result, + )) { + return; } + showDismissibleSnackBar( + context, + content: Text( + context.l10n.channels_publicChannelAdded, + ), + ); }, child: Text(dialogContext.l10n.common_add), ), @@ -1255,17 +1286,26 @@ class _ChannelsScreenState extends State if (dialogContext.mounted) { Navigator.pop(dialogContext); } - connector.setChannel(slot, channelName, psk); - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.channels_channelAdded( - channelName, - ), - ), - ); + final result = await connector.setChannel( + slot, + channelName, + psk, + ); + if (!context.mounted) return; + if (explainUnconfirmedChannelWrite( + context, + result, + )) { + return; } + showDismissibleSnackBar( + context, + content: Text( + context.l10n.channels_channelAdded( + channelName, + ), + ), + ); }, child: Text(dialogContext.l10n.common_add), ), @@ -1380,24 +1420,19 @@ class _ChannelsScreenState extends State // write and never loses the community. Uses the // screen's context, not the dialog's: this runs // after an await and the dialog may be gone. + int? slot; + var channelRefused = false; if (addPublicChannel && context.mounted) { - final slot = _allocateChannelSlot( + slot = _allocateChannelSlot( context, connector, ); - if (slot != null) { - final psk = community - .deriveCommunityPublicPsk(); - final channelName = - '${community.name} Public'; - connector.setChannel( - slot, - channelName, - psk, - ); - } + channelRefused = slot == null; } + // Closed before the write, which now waits for + // the radio: an open dialog would let a second + // tap create the community twice. if (dialogContext.mounted) { Navigator.pop(dialogContext); } @@ -1405,13 +1440,34 @@ class _ChannelsScreenState extends State // Refresh communities list _loadCommunities(); - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.community_created(name), - ), + if (slot != null) { + final result = await connector.setChannel( + slot, + '${community.name} Public', + community.deriveCommunityPublicPsk(), ); + if (context.mounted) { + channelRefused = + explainUnconfirmedChannelWrite( + context, + result, + ); + } + } + + if (context.mounted) { + // A refusal's message is showing and + // persists; this toast would replace it + // (#1026). The QR below still shows: the + // community was created either way. + if (!channelRefused) { + showDismissibleSnackBar( + context, + content: Text( + context.l10n.community_created(name), + ), + ); + } // Show QR code dialog await QrCodeShareDialog.show( @@ -1711,6 +1767,9 @@ class _ChannelsScreenState extends State ); return; } + if (refuseWhileChannelTableBusy(dialogContext, connector)) { + return; + } final Uint8List psk; if (channelType == ChannelType.hashtag) { @@ -1732,7 +1791,16 @@ class _ChannelsScreenState extends State Navigator.pop(dialogContext); try { - await connector.setChannel(channel.index, name, psk); + final result = await connector.editChannel( + channel, + name, + psk, + ); + if (result != ChannelWrite.ok) { + if (!context.mounted) return; + explainUnconfirmedChannelWrite(context, result); + return; + } await connector.setChannelCyr2LatEnabled( channel.index, cyr2latEnabled, @@ -1834,13 +1902,21 @@ class _ChannelsScreenState extends State ), TextButton( onPressed: () async { + if (refuseWhileChannelTableBusy(dialogContext, connector)) { + return; + } Navigator.pop(dialogContext); try { - await connector.deleteChannel(channel.index); + final result = await connector.deleteChannel(channel.index); - await channelMessageStore.clearChannelMessages(channel.index); + // Only on OK: if the radio kept the channel, it keeps its + // history too (#1026). + if (result == ChannelWrite.ok) { + await channelMessageStore.clearChannelMessages(channel.index); + } if (!context.mounted) return; + if (explainUnconfirmedChannelWrite(context, result)) return; showDismissibleSnackBar( context, @@ -1872,7 +1948,10 @@ class _ChannelsScreenState extends State ); } - void _addPublicChannel(BuildContext context, MeshCoreConnector connector) { + Future _addPublicChannel( + BuildContext context, + MeshCoreConnector connector, + ) async { // This used to write slot 0 unconditionally, with no occupancy check, so // it overwrote whatever was there (#1021). Public is identified by its PSK // (`Channel.isPublicChannel`), not by its index, so it has no claim on @@ -1887,7 +1966,9 @@ class _ChannelsScreenState extends State final slot = _allocateChannelSlot(context, connector); if (slot == null) return; final psk = Channel.parsePskHex(Channel.publicChannelPsk); - connector.setChannel(slot, 'Public', psk); + final result = await connector.setChannel(slot, 'Public', psk); + if (!context.mounted) return; + if (explainUnconfirmedChannelWrite(context, result)) return; showDismissibleSnackBar( context, content: Text(context.l10n.channels_publicChannelAdded), @@ -2108,23 +2189,42 @@ class _ChannelsScreenState extends State ), TextButton( onPressed: () async { + if (communityChannels.isNotEmpty && + refuseWhileChannelTableBusy(dialogContext, connector)) { + return; + } Navigator.pop(dialogContext); - // Delete all community channels from the device + // Delete all community channels from the device. Each delete is + // answered before the next goes out, and the list is re-read + // once at the end: a re-read between deletes would put the next + // one in the middle of a sync, where its reply cannot be told + // from the sync's (#1026). + ChannelWrite? failure; for (final channel in communityChannels) { - await connector.deleteChannel(channel.index); + final result = await connector.deleteChannel( + channel.index, + refresh: false, + ); + if (result != ChannelWrite.ok) failure ??= result; + } + if (communityChannels.isNotEmpty) { + await connector.getChannels(force: true); } // Remove community from store await _communityStore.removeCommunity(community.id); _loadCommunities(); - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.community_deleted(community.name)), - ); + if (!context.mounted) return; + if (failure != null && + explainUnconfirmedChannelWrite(context, failure)) { + return; } + showDismissibleSnackBar( + context, + content: Text(context.l10n.community_deleted(community.name)), + ); }, child: Text( dialogContext.l10n.community_delete, diff --git a/lib/screens/community_qr_scanner_screen.dart b/lib/screens/community_qr_scanner_screen.dart index f29711c4..bce2865e 100644 --- a/lib/screens/community_qr_scanner_screen.dart +++ b/lib/screens/community_qr_scanner_screen.dart @@ -231,8 +231,9 @@ class _CommunityQrScannerScreenState extends State { // // This used to skip the channel silently when the radio was full and then // show a green "joined" toast, which told the user everything had worked - // when the channel had not been added (#1021). A refusal now explains - // itself, and only a real success shows the green confirmation. + // when the channel had not been added (#1021). A refusal, or a write the + // radio did not confirm (#1026), now explains itself, and only a confirmed + // write shows the green confirmation. var channelRefused = false; if (addPublicChannel && context.mounted) { final connector = context.read(); @@ -242,7 +243,10 @@ class _CommunityQrScannerScreenState extends State { } else { final psk = community.deriveCommunityPublicPsk(); final channelName = '${community.name} Public'; - connector.setChannel(slot, channelName, psk); + final result = await connector.setChannel(slot, channelName, psk); + if (context.mounted) { + channelRefused = explainUnconfirmedChannelWrite(context, result); + } } } @@ -288,7 +292,7 @@ class _CommunityQrScannerScreenState extends State { // No slot is chosen here. It used to be, and that is the same bug the // channels screen had: the index was picked before the confirmation // dialog below and written after it, so a channel sync during the - // confirmation (setChannel itself starts one) could leave it pointing at + // confirmation (a channel write starts one) could leave it pointing at // an occupied slot. The slot is now chosen after the user confirms. if (!context.mounted) return; final confirmed = await showDialog( @@ -313,7 +317,14 @@ class _CommunityQrScannerScreenState extends State { // Refused: the persistent message explains why. Stay on this screen so // the user can retry, rather than popping away from the explanation. if (slot == null) return; - connector.setChannel(slot, channel.name, channel.psk); + final result = await connector.setChannel( + slot, + channel.name, + channel.psk, + ); + if (!context.mounted) return; + // Not confirmed: stay on this screen with the explanation showing. + if (explainUnconfirmedChannelWrite(context, result)) return; showDismissibleSnackBar( context, content: Text(context.l10n.channels_qrAdded(channel.name)), diff --git a/lib/services/stock_config_import_service.dart b/lib/services/stock_config_import_service.dart index 7c068042..af991ff5 100644 --- a/lib/services/stock_config_import_service.dart +++ b/lib/services/stock_config_import_service.dart @@ -74,8 +74,9 @@ class StockConfigImportResult { /// Sections whose commands were **sent** to the device without error. /// - /// This is not device confirmation. Apart from the identity import, which - /// waits for a real OK or ERR, the firmware's generic OK for these commands + /// This is not device confirmation. Apart from the identity import and the + /// channel writes, which wait for a real OK or ERR, the firmware's generic OK + /// for these commands /// is not currently awaited, so a frame lost or refused after it left our /// side would still land here. Wiring per-command confirmation is tracked /// separately; until then this set means "sent", and the UI says so rather @@ -92,7 +93,9 @@ class StockConfigImportResult { /// send count and not a confirmed count. final int contactsWritten; - /// Channels whose write command was sent. Same caveat as [contactsWritten]. + /// Channels the radio confirmed writing. Unlike [contactsWritten] this is a + /// confirmed count: a channel write waits for the radio's OK, and one it + /// refused or never answered is in [skippedChannels] instead (#1026). final int channelsAdded; bool get isComplete => failed.isEmpty && skippedChannels.isEmpty; @@ -278,17 +281,38 @@ class StockConfigImportService { existing: _connector.channels, incoming: incoming, maxChannels: _connector.maxChannels, - isSyncing: _connector.isSyncingChannels, + isSyncing: _connector.isChannelTableBusy, ); + // Each write is answered before the next goes out, and the list is + // re-read once at the end. A re-read after every write would put the next + // write in the middle of a sync, where its reply cannot be told from the + // sync's (#1026). + var added = 0; for (final assignment in plan.assignments) { - await _connector.setChannel( + final result = await _connector.setChannel( assignment.slot, assignment.channel.name, assignment.channel.secret, + refresh: false, ); + if (result == ChannelWrite.ok) { + added++; + } else { + skipped.add( + SkippedChannel( + assignment.channel.name, + result == ChannelWrite.noReply + ? StockConfigImportIssue.noReply + : StockConfigImportIssue.rejected, + ), + ); + } + } + if (plan.assignments.isNotEmpty) { + await _connector.getChannels(force: true); } skipped.addAll(plan.skipped); - return plan.assignments.length; + return added; } /// Upserts every contact. The firmware's add-or-update command keys on the diff --git a/test/connector/channel_write_reply_test.dart b/test/connector/channel_write_reply_test.dart new file mode 100644 index 00000000..c132f64d --- /dev/null +++ b/test/connector/channel_write_reply_test.dart @@ -0,0 +1,209 @@ +// #1026 (epic #1021): a channel write waits for the radio's OK or ERR, and a +// slot's message history is cleared only once the radio has said OK. +// +// Firmware with OffbandMesh/meshcore-firmware#1864 refuses a different channel +// over an occupied slot with ERR_CODE_BAD_STATE and keeps that channel intact. +// Clearing its history on the strength of having sent the frame would lose it. + +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/channel.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List psk(int fill) => Uint8List.fromList(List.filled(16, fill)); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late OffbandDatabase db; + late MeshCoreConnector connector; + late List sent; + + List setFrames() => + sent.where((f) => f.isNotEmpty && f[0] == cmdSetChannel).toList(); + + void ok() => connector.handleFrameForTest([respCodeOk]); + void err(int code) => connector.handleFrameForTest([respCodeErr, code]); + + /// The second write of a clear-then-add goes out only after the first has + /// been answered and its history cleared, which takes real async time. + Future untilSetFrames(int count) async { + for (var i = 0; i < 2000 && setFrames().length < count; i++) { + await Future.delayed(const Duration(milliseconds: 1)); + } + expect(setFrames(), hasLength(count)); + } + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + connector = MeshCoreConnector(); + connector.setConnectedForTest(); + sent = []; + connector.sendFrameOverrideForTest = sent.add; + connector.channelMessagesForTest[3] = []; + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + group('setChannel', () { + test('OK clears the slot\'s old history and reports ok', () async { + final write = connector.setChannel( + 3, + 'Weather', + psk(0x22), + refresh: false, + ); + ok(); + + expect(await write, ChannelWrite.ok); + expect(connector.channelMessagesForTest.containsKey(3), isFalse); + }); + + test('BAD_STATE is occupied, and the history stays', () async { + final write = connector.setChannel( + 3, + 'Weather', + psk(0x22), + refresh: false, + ); + err(errCodeBadState); + + expect(await write, ChannelWrite.occupied); + expect(connector.channelMessagesForTest.containsKey(3), isTrue); + }); + + test('any other ERR is rejected, and the history stays', () async { + final write = connector.setChannel( + 3, + 'Weather', + psk(0x22), + refresh: false, + ); + err(errCodeNotFound); + + expect(await write, ChannelWrite.rejected); + expect(connector.channelMessagesForTest.containsKey(3), isTrue); + }); + + test('no reply is noReply, and the history stays', () async { + connector.channelWriteReplyTimeout = const Duration(milliseconds: 20); + final write = connector.setChannel( + 3, + 'Weather', + psk(0x22), + refresh: false, + ); + + expect(await write, ChannelWrite.noReply); + expect(connector.channelMessagesForTest.containsKey(3), isTrue); + }); + + test('a timed-out write cannot take the next write\'s reply', () async { + connector.channelWriteReplyTimeout = const Duration(milliseconds: 20); + expect( + await connector.setChannel(3, 'A', psk(0x22), refresh: false), + ChannelWrite.noReply, + ); + + connector.channelWriteReplyTimeout = const Duration(seconds: 5); + final second = connector.setChannel(4, 'B', psk(0x33), refresh: false); + err(errCodeBadState); + + expect(await second, ChannelWrite.occupied); + }); + + test('the table is busy until the radio answers', () async { + final write = connector.setChannel( + 3, + 'Weather', + psk(0x22), + refresh: false, + ); + expect(connector.isChannelTableBusy, isTrue); + + ok(); + await write; + expect(connector.isChannelTableBusy, isFalse); + }); + + test('disconnected sends nothing and reports noReply', () async { + final fresh = MeshCoreConnector(); + fresh.sendFrameOverrideForTest = sent.add; + + expect( + await fresh.setChannel(3, 'Weather', psk(0x22)), + ChannelWrite.noReply, + ); + expect(sent, isEmpty); + }); + }); + + group('deleteChannel', () { + test('OK clears the history', () async { + final delete = connector.deleteChannel(3, refresh: false); + ok(); + + expect(await delete, ChannelWrite.ok); + expect(connector.channelMessagesForTest.containsKey(3), isFalse); + }); + + test('a refusal keeps the history', () async { + final delete = connector.deleteChannel(3, refresh: false); + err(errCodeNotFound); + + expect(await delete, ChannelWrite.rejected); + expect(connector.channelMessagesForTest.containsKey(3), isTrue); + }); + }); + + group('editChannel', () { + final current = Channel(index: 3, name: 'Weather', psk: psk(0x22)); + + test('a rename is one write and keeps the history', () async { + final edit = connector.editChannel(current, 'Wx', psk(0x22)); + ok(); + + expect(await edit, ChannelWrite.ok); + expect(setFrames(), hasLength(1)); + expect(connector.channelMessagesForTest.containsKey(3), isTrue); + }); + + test('a new key is clear-then-add, so #1864 firmware accepts it', () async { + final edit = connector.editChannel(current, 'Weather', psk(0x99)); + await untilSetFrames(1); + // The clear: an empty name. + expect(setFrames()[0][2], 0); + ok(); + + await untilSetFrames(2); + expect(setFrames()[1].sublist(2 + 32, 2 + 32 + 16), psk(0x99)); + ok(); + + expect(await edit, ChannelWrite.ok); + expect(connector.channelMessagesForTest.containsKey(3), isFalse); + }); + + test('a refused clear writes nothing more and keeps the history', () async { + final edit = connector.editChannel(current, 'Weather', psk(0x99)); + await untilSetFrames(1); + err(errCodeNotFound); + + expect(await edit, ChannelWrite.rejected); + expect(setFrames(), hasLength(1)); + expect(connector.channelMessagesForTest.containsKey(3), isTrue); + }); + }); +} diff --git a/untranslated.json b/untranslated.json index 4bb2074f..8d5234e7 100644 --- a/untranslated.json +++ b/untranslated.json @@ -157,6 +157,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -530,6 +533,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -903,6 +909,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -1276,6 +1285,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -1649,6 +1661,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2022,6 +2037,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2395,6 +2413,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2768,6 +2789,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3141,6 +3165,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3514,6 +3541,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3887,6 +3917,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -4260,6 +4293,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -4633,6 +4669,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -5006,6 +5045,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -5379,6 +5421,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -5752,6 +5797,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -6125,6 +6173,9 @@ "channels_slotBusySyncing", "channels_slotsAllFull", "channels_publicAlreadyAdded", + "channels_writeOccupied", + "channels_writeRejected", + "channels_writeNoReply", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", From 661c39dd0d1f4908dd7d9a6197702d9e01b14b43 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:53:30 -0400 Subject: [PATCH 4/7] test(#1024): every channel refusal shows, persists, and is absent on success Part A of the #1021 test child. Widget tests (test/helpers/channel_slot_ui_test.dart) for all six refusal messages: busy, all slots full (with the count), Public already on the radio, and the three unconfirmed-write outcomes (occupied, rejected, no reply). Each one shows on its own failure, is still on screen 10 seconds later (past the 4 second toast default), and none shows when the action is allowed. Connector test: a channel sync that fails restores the cached list with hasLoadedChannels false, and the table still reads as not busy, so an add gets a free slot. This is the lockout a hasLoadedChannels gate would have caused on a flaky link, driven through the real sync rather than asserted. The "Public is already on this radio" check moves from the channels screen into channel_slot_ui.dart, so all six messages live in one tested place. Mutation-checked: dropping persist: true fails all 7 persistence tests; gating the table on hasLoadedChannels fails the failed-sync test. Full suite 1805 pass, analyze clean. Part B (on-device) is the owner's hardware pass. Co-Authored-By: Claude Opus 5.5 --- lib/helpers/channel_slot_ui.dart | 13 ++ lib/screens/channels_screen.dart | 8 +- test/connector/channel_write_reply_test.dart | 44 +++++ test/helpers/channel_slot_ui_test.dart | 186 +++++++++++++++++++ 4 files changed, 244 insertions(+), 7 deletions(-) create mode 100644 test/helpers/channel_slot_ui_test.dart diff --git a/lib/helpers/channel_slot_ui.dart b/lib/helpers/channel_slot_ui.dart index 95a6e702..c49d47d2 100644 --- a/lib/helpers/channel_slot_ui.dart +++ b/lib/helpers/channel_slot_ui.dart @@ -78,6 +78,19 @@ bool explainUnconfirmedChannelWrite(BuildContext context, ChannelWrite result) { return true; } +/// Refuses a second Public channel, and says so. Returns true if it refused. +/// +/// Public is identified by its PSK (`Channel.isPublicChannel`), not by slot 0, +/// so it can live in any slot and this is the only duplicate check it needs. +bool refusePublicAlreadyOnRadio( + BuildContext context, + MeshCoreConnector connector, +) { + if (!connector.channels.any((c) => c.isPublicChannel)) return false; + showChannelBlockedMessage(context, context.l10n.channels_publicAlreadyAdded); + return true; +} + /// For an edit or delete: refuses while the channel list is being re-read or /// a write is unanswered, and says so. Returns true if it refused. /// diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 484f1983..81a83031 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -1956,13 +1956,7 @@ class _ChannelsScreenState extends State // it overwrote whatever was there (#1021). Public is identified by its PSK // (`Channel.isPublicChannel`), not by its index, so it has no claim on // slot 0 and can live anywhere. - if (connector.channels.any((c) => c.isPublicChannel)) { - showChannelBlockedMessage( - context, - context.l10n.channels_publicAlreadyAdded, - ); - return; - } + if (refusePublicAlreadyOnRadio(context, connector)) return; final slot = _allocateChannelSlot(context, connector); if (slot == null) return; final psk = Channel.parsePskHex(Channel.publicChannelPsk); diff --git a/test/connector/channel_write_reply_test.dart b/test/connector/channel_write_reply_test.dart index c132f64d..39f5f58c 100644 --- a/test/connector/channel_write_reply_test.dart +++ b/test/connector/channel_write_reply_test.dart @@ -11,6 +11,7 @@ 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/helpers/channel_slot_decision.dart'; import 'package:meshcore_open/models/channel.dart'; import 'package:meshcore_open/storage/drift/blob_store.dart'; import 'package:meshcore_open/storage/drift/offband_database.dart'; @@ -206,4 +207,47 @@ void main() { expect(connector.channelMessagesForTest.containsKey(3), isTrue); }); }); + + // #1024: after a FAILED sync the cached list is restored but + // hasLoadedChannels stays false. Gating adds on hasLoadedChannels would lock + // the user out of adding channels on a flaky link, so the table has to read + // as usable here, driven through the real sync rather than asserted. + group('after a failed sync', () { + List channelInfo(int index, String name, int fill) => [ + respCodeChannelInfo, + index, + ...name.codeUnits, + ...List.filled(32 - name.length, 0), + ...psk(fill), + ]; + + Future settle() => Future.delayed(Duration.zero); + + test( + 'the restored list is not busy, and an add gets a free slot', + () async { + await connector.getChannels(maxChannels: 2, force: true); + connector.handleFrameForTest(channelInfo(0, 'Public', 0x11)); + await settle(); + connector.handleFrameForTest(channelInfo(1, 'Weather', 0x22)); + await settle(); + expect(connector.hasLoadedChannels, isTrue); + + connector.sendFrameOverrideForTest = (_) => + throw Exception('link lost'); + await connector.getChannels(maxChannels: 2, force: true); + await settle(); + + expect(connector.hasLoadedChannels, isFalse); + expect(connector.channels.map((c) => c.index), unorderedEquals([0, 1])); + expect(connector.isChannelTableBusy, isFalse); + final decision = decideChannelSlot( + channels: connector.channels, + maxChannels: 3, + isSyncing: connector.isChannelTableBusy, + ); + expect(decision.slot, 2); + }, + ); + }); } diff --git a/test/helpers/channel_slot_ui_test.dart b/test/helpers/channel_slot_ui_test.dart new file mode 100644 index 00000000..7fa56c2c --- /dev/null +++ b/test/helpers/channel_slot_ui_test.dart @@ -0,0 +1,186 @@ +// #1024 (epic #1021): every channel refusal message shows on its own failure, +// stays until dismissed, and is absent when the action is allowed. +// +// The messages are the whole point of the owner's ruling: block the unsafe +// write, keep the control live, and say why. A message that never shows, or +// that disappears in four seconds, is the silent failure that ruling rejects. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/helpers/channel_slot_ui.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/channel.dart'; + +class _FakeConn extends MeshCoreConnector { + _FakeConn({this.list = const [], this.max = 40, this.busy = false}); + + final List list; + final int max; + final bool busy; + + @override + List get channels => list; + @override + int get maxChannels => max; + @override + bool get isChannelTableBusy => busy; +} + +Channel _ch(int index, String name, int fill) => Channel( + index: index, + name: name, + psk: Channel.parsePskHex(List.filled(32, fill.toRadixString(16)).join()), +); + +final _l10n = lookupAppLocalizations(const Locale('en')); + +/// Every refusal this file can show, so a success can assert none of them. +final _allMessages = [ + _l10n.channels_slotBusySyncing, + _l10n.channels_slotsAllFull(3), + _l10n.channels_publicAlreadyAdded, + _l10n.channels_writeOccupied, + _l10n.channels_writeRejected, + _l10n.channels_writeNoReply, +]; + +Future _host(WidgetTester tester) async { + late BuildContext context; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (c) { + context = c; + return const SizedBox.shrink(); + }, + ), + ), + ), + ); + return context; +} + +/// Shown, and still shown well past the 4 second toast default. +Future _expectPersistent(WidgetTester tester, String message) async { + await tester.pump(); + expect(find.text(message), findsOneWidget); + await tester.pump(const Duration(seconds: 10)); + expect(find.text(message), findsOneWidget); +} + +Future _expectNoRefusal(WidgetTester tester) async { + await tester.pump(); + for (final message in _allMessages) { + expect(find.text(message), findsNothing, reason: message); + } +} + +void main() { + group('allocateChannelSlotOrExplain', () { + testWidgets('busy: refused, with the busy message', (tester) async { + final context = await _host(tester); + final slot = allocateChannelSlotOrExplain(context, _FakeConn(busy: true)); + + expect(slot, isNull); + await _expectPersistent(tester, _l10n.channels_slotBusySyncing); + }); + + testWidgets('full: refused, naming the slot count', (tester) async { + final context = await _host(tester); + final slot = allocateChannelSlotOrExplain( + context, + _FakeConn( + list: [_ch(0, 'A', 1), _ch(1, 'B', 2), _ch(2, 'C', 3)], + max: 3, + ), + ); + + expect(slot, isNull); + await _expectPersistent(tester, _l10n.channels_slotsAllFull(3)); + }); + + testWidgets('a free slot: allowed, and no message', (tester) async { + final context = await _host(tester); + final slot = allocateChannelSlotOrExplain( + context, + _FakeConn(list: [_ch(0, 'A', 1)], max: 3), + ); + + expect(slot, 1); + await _expectNoRefusal(tester); + }); + }); + + group('refusePublicAlreadyOnRadio', () { + testWidgets('Public present, in any slot: refused', (tester) async { + final context = await _host(tester); + final publicPsk = Channel.parsePskHex(Channel.publicChannelPsk); + final refused = refusePublicAlreadyOnRadio( + context, + _FakeConn( + list: [Channel(index: 5, name: 'Public', psk: publicPsk)], + ), + ); + + expect(refused, isTrue); + await _expectPersistent(tester, _l10n.channels_publicAlreadyAdded); + }); + + testWidgets('no Public: allowed, and no message', (tester) async { + final context = await _host(tester); + final refused = refusePublicAlreadyOnRadio( + context, + _FakeConn(list: [_ch(0, 'A', 1)]), + ); + + expect(refused, isFalse); + await _expectNoRefusal(tester); + }); + }); + + group('explainUnconfirmedChannelWrite', () { + final cases = { + ChannelWrite.occupied: _l10n.channels_writeOccupied, + ChannelWrite.rejected: _l10n.channels_writeRejected, + ChannelWrite.noReply: _l10n.channels_writeNoReply, + }; + for (final entry in cases.entries) { + testWidgets('${entry.key.name}: explained, persistently', (tester) async { + final context = await _host(tester); + + expect(explainUnconfirmedChannelWrite(context, entry.key), isTrue); + await _expectPersistent(tester, entry.value); + }); + } + + testWidgets('ok: nothing to explain, and no message', (tester) async { + final context = await _host(tester); + + expect(explainUnconfirmedChannelWrite(context, ChannelWrite.ok), isFalse); + await _expectNoRefusal(tester); + }); + }); + + group('refuseWhileChannelTableBusy', () { + testWidgets('busy: refused, with the busy message', (tester) async { + final context = await _host(tester); + + expect( + refuseWhileChannelTableBusy(context, _FakeConn(busy: true)), + isTrue, + ); + await _expectPersistent(tester, _l10n.channels_slotBusySyncing); + }); + + testWidgets('idle: allowed, and no message', (tester) async { + final context = await _host(tester); + + expect(refuseWhileChannelTableBusy(context, _FakeConn()), isFalse); + await _expectNoRefusal(tester); + }); + }); +} From bf8602512affe749c6c7af60544e6a859dc68971 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Sat, 7 Nov 2026 04:21:33 -0500 Subject: [PATCH 5/7] fix(#1025): reconcile the epic with dev's PSK-keyed history Rebasing Epic #1021 onto dev met #1063, which keys channel history by the channel's PSK. On a slot reassignment it keeps the old channel's history, so re-adding that channel brings it back, and only a delete removes history outright. #1026's write path had cleared history on every change; the rebase resolution moves it onto dev's rules. A confirmed reassignment (an add, or an edit to a new key) purges only the slot's legacy keys and the in-memory entry. A confirmed delete removes history outright. All three still happen only after the radio's OK. Nothing in dev's suite caught a reassignment true-deleting the old channel's history: with that mutation applied, all tests passed. A new test (channel_write_history_identity_test.dart) drives the real PSK-keyed store and fails 2 of 4 under it. The Edit Channel dialog now checks for a busy channel table before #1103's identity check. Mid-sync the list is empty, so the identity check closed the dialog and blamed a changed channel. The busy check keeps the dialog and the user's edits open and gives the real reason. #1060's restoreChannelsToRadio now counts as a channel write in flight while it runs, so an add made during a restore is refused instead of choosing a slot the restore is about to fill (in the rebased #1026 commit). Full suite 1954 + 4 pass, analyze clean. Co-Authored-By: Claude Opus 5.5 --- lib/screens/channels_screen.dart | 13 +- .../channel_write_history_identity_test.dart | 128 ++++++++++++++++++ 2 files changed, 136 insertions(+), 5 deletions(-) create mode 100644 test/connector/channel_write_history_identity_test.dart diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 81a83031..8a51269d 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -1747,12 +1747,18 @@ class _ChannelsScreenState extends State return; } + // Checked first: mid-sync the list is empty, so the identity + // check below would close the dialog and blame a changed + // channel. This keeps the dialog, and the user's edits, open + // and gives the real reason (#1021, #1026). + if (refuseWhileChannelTableBusy(dialogContext, connector)) { + return; + } // #1103 review: this dialog captured the channel when it // opened. If a sync replaced the slot's identity meanwhile // (the #1060 class), writing by the captured index would hit // the NEW occupant with the OLD dialog's rules. Refuse the - // write and say why; mid-sync the list is empty, so this - // also fails closed while slots are unconfirmed. + // write and say why. final live = connector.channels.cast().firstWhere( (c) => c?.index == channel.index, orElse: () => null, @@ -1767,9 +1773,6 @@ class _ChannelsScreenState extends State ); return; } - if (refuseWhileChannelTableBusy(dialogContext, connector)) { - return; - } final Uint8List psk; if (channelType == ChannelType.hashtag) { diff --git a/test/connector/channel_write_history_identity_test.dart b/test/connector/channel_write_history_identity_test.dart new file mode 100644 index 00000000..a1e3dc78 --- /dev/null +++ b/test/connector/channel_write_history_identity_test.dart @@ -0,0 +1,128 @@ +// #1026 on top of #1063: what a confirmed channel write does to PSK-keyed +// history. +// +// History is keyed by the channel's PSK (#194). Giving a slot to a different +// channel is a reassignment: the old channel's history is kept, so it comes +// back if that channel is ever re-added (#1063). Deleting a channel is the one +// path that removes its history outright. Both happen only after the radio's +// OK (#1026). Exercised through the real store, not the in-memory map. + +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/channel.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'; + +Uint8List psk(int fill) => Uint8List.fromList(List.filled(16, fill)); + +List channelInfo(int index, String name, Uint8List key) => [ + respCodeChannelInfo, + index, + ...name.codeUnits, + ...List.filled(32 - name.length, 0), + ...key, +]; + +ChannelMessage msg(String text) => ChannelMessage( + senderName: 's', + text: text, + timestamp: DateTime.fromMillisecondsSinceEpoch(1000), + isOutgoing: false, + channelIndex: 0, + messageId: text, +); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late OffbandDatabase db; + late MeshCoreConnector connector; + + final weather = Channel(index: 0, name: 'Weather', psk: psk(0x22)); + + /// Reads the history stored under [weather]'s PSK, whatever slot it is in. + late ChannelMessageStore weatherHistory; + + Future settle() => Future.delayed(Duration.zero); + void ok() => connector.handleFrameForTest([respCodeOk]); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + connector = MeshCoreConnector(); + connector.sendFrameOverrideForTest = (_) {}; + connector.setConnectedForTest(); + connector.setSelfPublicKeyForTest( + Uint8List.fromList(List.generate(32, (i) => i)), + ); + connector.wireMessageStoreForTest(); + + // The radio holds Weather in slot 0. + await connector.getChannels(maxChannels: 1, force: true); + connector.handleFrameForTest(channelInfo(0, weather.name, weather.psk)); + await settle(); + expect(connector.channels.single.pskHex, weather.pskHex); + + weatherHistory = ChannelMessageStore() + ..setPublicKeyHex = connector.selfPublicKeyHex + ..channelPskResolver = (_) => weather.pskHex; + await weatherHistory.saveChannelMessages(0, [msg('kept')]); + expect(await weatherHistory.loadChannelMessages(0), hasLength(1)); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + test( + 'a slot given to another channel keeps the old one\'s history', + () async { + final write = connector.setChannel(0, 'Other', psk(0x33), refresh: false); + ok(); + + expect(await write, ChannelWrite.ok); + expect(await weatherHistory.loadChannelMessages(0), hasLength(1)); + }, + ); + + test('a new key by edit keeps the old key\'s history too', () async { + final edit = connector.editChannel(weather, 'Weather', psk(0x99)); + await settle(); + ok(); // the clear + for (var i = 0; i < 50; i++) { + await settle(); + } + ok(); // the add + + expect(await edit, ChannelWrite.ok); + expect(await weatherHistory.loadChannelMessages(0), hasLength(1)); + }); + + test('a confirmed delete removes the channel\'s history', () async { + final delete = connector.deleteChannel(0, refresh: false); + ok(); + + expect(await delete, ChannelWrite.ok); + expect(await weatherHistory.loadChannelMessages(0), isEmpty); + }); + + test('a refused delete keeps it', () async { + final delete = connector.deleteChannel(0, refresh: false); + connector.handleFrameForTest([respCodeErr, errCodeNotFound]); + + expect(await delete, ChannelWrite.rejected); + expect(await weatherHistory.loadChannelMessages(0), hasLength(1)); + }); +} From 085843f758513b8c8896e1b72c28dd7e61c892e8 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Sat, 7 Nov 2026 04:34:39 -0500 Subject: [PATCH 6/7] fix(#1025): no sync shares the reply queue with a channel write Gemini review findings on Epic #1021, after verifying each against the code. Kept, fixed: - A sync started while a channel write waits for its reply shares the ordered reply queue with it, so the sync's empty-slot ERR could be taken as the write's answer. The trigger is real even though the review named a path that doesn't exist: pull-to-refresh, the sync button, the 400 ms channel-changed debounce, and dev's 3 s failed-sync retry all call getChannels at any time. getChannels now defers while a write is in flight, and the last write to finish runs it once. The writers' own re-reads call _syncChannels directly. - Config import and community delete hold the guard across their whole loop (batchChannelWrites), so a deferred sync cannot start between two writes. - A key change whose clear lands but whose add fails used to report "did not confirm the change", understating that the channel is now gone. It returns ChannelWrite.clearedNotAdded, with a message saying the slot is empty and to add the channel again. Justified, not changed: - A reply arriving after the 5 s timeout, once the waiter has been dropped, shifts the queue by one. Keeping the waiter instead would shift it permanently whenever a reply is truly lost. Firmware answers CMD_SET_CHANNEL synchronously, far inside 5 s, and a disconnect clears the queue, so dropping is the smaller risk. - Claimed crash on removeAt(0) with an empty queue: both handlers check isEmpty first. Mutation-checked: removing the deferral fails 2 tests; returning the add's own result fails 1. Full suite 1962 pass, analyze clean. Co-Authored-By: Claude Opus 5.5 --- lib/connector/meshcore_connector.dart | 75 +++++++++++++++---- lib/helpers/channel_slot_ui.dart | 1 + lib/l10n/app_en.arb | 4 + 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/channels_screen.dart | 24 +++--- lib/services/stock_config_import_service.dart | 47 ++++++------ test/connector/channel_write_reply_test.dart | 53 +++++++++++++ test/helpers/channel_slot_ui_test.dart | 2 + untranslated.json | 17 +++++ 27 files changed, 255 insertions(+), 46 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 081eadde..ac985edb 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -229,6 +229,10 @@ enum ChannelWrite { /// Not connected, or no reply before the timeout. The write may or may not /// have landed. noReply, + + /// An edit to a new key cleared the old channel, but the new one was not + /// confirmed, so the slot is now empty. (#1026) + clearedNotAdded, } /// Result of [MeshCoreConnector.exportPrivateKey]. [identity] is @@ -6901,6 +6905,19 @@ class MeshCoreConnector extends ChangeNotifier { } Future getChannels({int? maxChannels, bool force = false}) async { + // A sync started while a channel write waits for its reply would share the + // reply queue with it. Replies are matched by order, so the sync's + // empty-slot ERR could be taken as the write's answer. Deferred until the + // writes finish, then run once (#1026). The writers' own re-reads call + // [_syncChannels] directly. + if (_channelWritesInFlight > 0) { + _channelSyncDeferredByWrite = true; + return; + } + return _syncChannels(maxChannels: maxChannels, force: force); + } + + Future _syncChannels({int? maxChannels, bool force = false}) async { if (!isConnected) return; if (_isSyncingChannels) { debugPrint('[ChannelSync] Already syncing channels, ignoring request'); @@ -7255,6 +7272,7 @@ class MeshCoreConnector extends ChangeNotifier { Duration channelWriteReplyTimeout = const Duration(seconds: 5); int _channelWritesInFlight = 0; + bool _channelSyncDeferredByWrite = false; /// True while the channel list cannot be trusted to show which slots are /// free: a sync is re-reading it, or a write has not been answered yet. A @@ -7262,6 +7280,30 @@ class MeshCoreConnector extends ChangeNotifier { bool get isChannelTableBusy => _isSyncingChannels || _channelWritesInFlight > 0; + void _beginChannelWrite() => _channelWritesInFlight++; + + /// Ends one write; the last one to end runs any sync that [getChannels] + /// deferred while writes were waiting for their replies. + void _endChannelWrite() { + _channelWritesInFlight--; + if (_channelWritesInFlight == 0 && _channelSyncDeferredByWrite) { + _channelSyncDeferredByWrite = false; + unawaited(_syncChannels(force: true)); + } + } + + /// Runs several channel writes as one, so no sync or other add can start + /// between two of them. Each write inside passes `refresh: false`, and the + /// caller re-reads the list once afterwards. (#1026) + Future batchChannelWrites(Future Function() writes) async { + _beginChannelWrite(); + try { + return await writes(); + } finally { + _endChannelWrite(); + } + } + /// Writes the client's cached channel list back onto the radio (#1060). /// /// For a radio that lost channel storage (reflash, wipe) the client's cache @@ -7289,7 +7331,7 @@ class MeshCoreConnector extends ChangeNotifier { // Counted as a write in flight for its whole length, so an add made while // it runs is refused instead of choosing a slot this is about to fill // (#1021, #1026). - _channelWritesInFlight++; + _beginChannelWrite(); try { var sent = 0; for (final channel in toRestore) { @@ -7318,10 +7360,10 @@ class MeshCoreConnector extends ChangeNotifier { // the radio has not answered for yet and report 0 every time. The // authoritative feedback is the erased-slot banner, which is re-derived // on every sync and therefore stays up if some writes did not land. - await getChannels(force: true); + await _syncChannels(force: true); return sent; } finally { - _channelWritesInFlight--; + _endChannelWrite(); } } @@ -7354,6 +7396,10 @@ class MeshCoreConnector extends ChangeNotifier { /// A new key is a slot reassignment for history purposes, the same as /// before the clear-then-add: the old key's PSK-keyed history is kept, so /// it comes back if that key is ever re-added (#1063). + /// + /// If the clear lands and the add does not, the slot is left empty and this + /// returns [ChannelWrite.clearedNotAdded], so the user is told the channel is + /// gone rather than that the change may not have happened. Future editChannel( Channel channel, String name, @@ -7369,29 +7415,32 @@ class MeshCoreConnector extends ChangeNotifier { refresh: true, ); } - _channelWritesInFlight++; + _beginChannelWrite(); try { final cleared = await _writeChannelSlot(channel.index, '', Uint8List(16)); if (cleared != ChannelWrite.ok) { - await getChannels(force: true); + await _syncChannels(force: true); return cleared; } await _retireSlotOccupant(channel.index); - return await _setChannel( + final added = await _setChannel( channel.index, name, psk, occupantPsk: null, refresh: true, ); + return added == ChannelWrite.ok + ? ChannelWrite.ok + : ChannelWrite.clearedNotAdded; } finally { - _channelWritesInFlight--; + _endChannelWrite(); } } Future deleteChannel(int index, {bool refresh = true}) async { if (!isConnected) return ChannelWrite.noReply; - _channelWritesInFlight++; + _beginChannelWrite(); try { // A slot is deleted by writing an empty name and a zero PSK. Its history // goes outright (the true-delete path, #1063), once the radio has said @@ -7401,10 +7450,10 @@ class MeshCoreConnector extends ChangeNotifier { await _channelMessageStore.clearChannelMessages(index); _channelMessages.remove(index); } - if (refresh) await getChannels(force: true); + if (refresh) await _syncChannels(force: true); return result; } finally { - _channelWritesInFlight--; + _endChannelWrite(); } } @@ -7415,7 +7464,7 @@ class MeshCoreConnector extends ChangeNotifier { required Uint8List? occupantPsk, required bool refresh, }) async { - _channelWritesInFlight++; + _beginChannelWrite(); try { // A rename (same PSK) keeps everything; a different PSK retires the // slot's previous occupant (see [_retireSlotOccupant]). @@ -7431,10 +7480,10 @@ class MeshCoreConnector extends ChangeNotifier { // Re-read on every outcome: after a refusal the list we chose the slot // from was wrong, and after no reply nobody knows what the slot holds. - if (refresh) await getChannels(force: true); + if (refresh) await _syncChannels(force: true); return result; } finally { - _channelWritesInFlight--; + _endChannelWrite(); } } diff --git a/lib/helpers/channel_slot_ui.dart b/lib/helpers/channel_slot_ui.dart index c49d47d2..7df68c6f 100644 --- a/lib/helpers/channel_slot_ui.dart +++ b/lib/helpers/channel_slot_ui.dart @@ -72,6 +72,7 @@ bool explainUnconfirmedChannelWrite(BuildContext context, ChannelWrite result) { ChannelWrite.occupied => l10n.channels_writeOccupied, ChannelWrite.rejected => l10n.channels_writeRejected, ChannelWrite.noReply => l10n.channels_writeNoReply, + ChannelWrite.clearedNotAdded => l10n.channels_writeClearedNotAdded, }; if (message == null) return false; showChannelBlockedMessage(context, message); diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 4b1c14bc..6f47574b 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1054,6 +1054,10 @@ "@channels_writeNoReply": { "description": "A channel write got no reply before the timeout, or the radio is not connected; it may or may not have landed. Persistent (#1026)." }, + "channels_writeClearedNotAdded": "The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.", + "@channels_writeClearedNotAdded": { + "description": "A channel key change is clear-then-add; the clear landed and the add did not, so the edited channel is gone from the radio. Persistent (#1026)." + }, "channels_sortBy": "Sort by", "channels_sortManual": "Manual", "channels_sortAZ": "A-Z", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 90811d09..95cec203 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3268,6 +3268,12 @@ abstract class AppLocalizations { /// **'The radio did not confirm the change. Check the channel list before trying again.'** String get channels_writeNoReply; + /// A channel key change is clear-then-add; the clear landed and the add did not, so the edited channel is gone from the radio. Persistent (#1026). + /// + /// In en, this message translates to: + /// **'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'** + String get channels_writeClearedNotAdded; + /// No description provided for @channels_sortBy. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 68e444e6..9a1b3536 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1858,6 +1858,10 @@ class AppLocalizationsBg extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Сортирай по'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 2c8880f5..28b102e3 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1853,6 +1853,10 @@ class AppLocalizationsDe extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Sortiere nach'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index dd9adba4..be9702e2 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1831,6 +1831,10 @@ class AppLocalizationsEn extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Sort by'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index e1b42311..153c50dd 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1854,6 +1854,10 @@ class AppLocalizationsEs extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Ordenar por'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 3891d61d..a91f95be 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1859,6 +1859,10 @@ class AppLocalizationsFr extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Trier par'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index d8f57f14..c3923965 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1859,6 +1859,10 @@ class AppLocalizationsHu extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Szűrés'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 29257893..256dd7cb 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1856,6 +1856,10 @@ class AppLocalizationsIt extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Ordina per'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index f091f2a6..64b5e75a 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1797,6 +1797,10 @@ class AppLocalizationsJa extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => '並び替え'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index b967e75d..52c18a85 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1792,6 +1792,10 @@ class AppLocalizationsKo extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => '정렬 기준 선택'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index aa9c204f..7ba0f3ab 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1844,6 +1844,10 @@ class AppLocalizationsNl extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Sorteren door'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index ea1fedc1..adbdba82 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1865,6 +1865,10 @@ class AppLocalizationsPl extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Sortuj po'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 382ae0a5..aba7e8b2 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1853,6 +1853,10 @@ class AppLocalizationsPt extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Ordenar por'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 3bc353bf..06fe6abc 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1854,6 +1854,10 @@ class AppLocalizationsRu extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Сортировка'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0ee32439..035a572a 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1845,6 +1845,10 @@ class AppLocalizationsSk extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Triediť podľa'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index b1c21333..a6ba1ce0 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1842,6 +1842,10 @@ class AppLocalizationsSl extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Sortiraj po'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 054e1c97..fad12bcf 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1834,6 +1834,10 @@ class AppLocalizationsSv extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Sortera efter'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 23dd9a56..9c3dfb30 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1849,6 +1849,10 @@ class AppLocalizationsUk extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => 'Сортувати за'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 3d470f89..348f8e1d 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1778,6 +1778,10 @@ class AppLocalizationsZh extends AppLocalizations { String get channels_writeNoReply => 'The radio did not confirm the change. Check the channel list before trying again.'; + @override + String get channels_writeClearedNotAdded => + 'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'; + @override String get channels_sortBy => '排序方式'; diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 8a51269d..a49b2046 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -2194,17 +2194,19 @@ class _ChannelsScreenState extends State // Delete all community channels from the device. Each delete is // answered before the next goes out, and the list is re-read - // once at the end: a re-read between deletes would put the next - // one in the middle of a sync, where its reply cannot be told - // from the sync's (#1026). - ChannelWrite? failure; - for (final channel in communityChannels) { - final result = await connector.deleteChannel( - channel.index, - refresh: false, - ); - if (result != ChannelWrite.ok) failure ??= result; - } + // once at the end. A sync between two deletes would share their + // reply queue, so the loop runs as one batch (#1026). + final failure = await connector.batchChannelWrites(() async { + ChannelWrite? first; + for (final channel in communityChannels) { + final result = await connector.deleteChannel( + channel.index, + refresh: false, + ); + if (result != ChannelWrite.ok) first ??= result; + } + return first; + }); if (communityChannels.isNotEmpty) { await connector.getChannels(force: true); } diff --git a/lib/services/stock_config_import_service.dart b/lib/services/stock_config_import_service.dart index af991ff5..425d7f12 100644 --- a/lib/services/stock_config_import_service.dart +++ b/lib/services/stock_config_import_service.dart @@ -284,30 +284,33 @@ class StockConfigImportService { isSyncing: _connector.isChannelTableBusy, ); // Each write is answered before the next goes out, and the list is - // re-read once at the end. A re-read after every write would put the next - // write in the middle of a sync, where its reply cannot be told from the - // sync's (#1026). - var added = 0; - for (final assignment in plan.assignments) { - final result = await _connector.setChannel( - assignment.slot, - assignment.channel.name, - assignment.channel.secret, - refresh: false, - ); - if (result == ChannelWrite.ok) { - added++; - } else { - skipped.add( - SkippedChannel( - assignment.channel.name, - result == ChannelWrite.noReply - ? StockConfigImportIssue.noReply - : StockConfigImportIssue.rejected, - ), + // re-read once at the end. A sync between two writes would share their + // reply queue, where a write's reply cannot be told from the sync's, so + // the whole loop runs as one batch (#1026). + final added = await _connector.batchChannelWrites(() async { + var count = 0; + for (final assignment in plan.assignments) { + final result = await _connector.setChannel( + assignment.slot, + assignment.channel.name, + assignment.channel.secret, + refresh: false, ); + if (result == ChannelWrite.ok) { + count++; + } else { + skipped.add( + SkippedChannel( + assignment.channel.name, + result == ChannelWrite.noReply + ? StockConfigImportIssue.noReply + : StockConfigImportIssue.rejected, + ), + ); + } } - } + return count; + }); if (plan.assignments.isNotEmpty) { await _connector.getChannels(force: true); } diff --git a/test/connector/channel_write_reply_test.dart b/test/connector/channel_write_reply_test.dart index 39f5f58c..4cda5921 100644 --- a/test/connector/channel_write_reply_test.dart +++ b/test/connector/channel_write_reply_test.dart @@ -206,6 +206,59 @@ void main() { expect(setFrames(), hasLength(1)); expect(connector.channelMessagesForTest.containsKey(3), isTrue); }); + + test( + 'a clear that lands and an add that fails says the slot is empty', + () async { + final edit = connector.editChannel(current, 'Weather', psk(0x99)); + await untilSetFrames(1); + ok(); // the clear lands + + await untilSetFrames(2); + err(errCodeNotFound); // the add does not + + expect(await edit, ChannelWrite.clearedNotAdded); + }, + ); + }); + + // Gemini review of #1021: a sync started while a write waits for its reply + // shares the reply queue with it, so the sync's empty-slot ERR could be + // taken as the write's answer. The sync waits for the writes instead. + group('a sync requested during a write', () { + List getFrames() => + sent.where((f) => f.isNotEmpty && f[0] == cmdGetChannel).toList(); + + test('is deferred until the reply, then runs', () async { + final write = connector.setChannel(3, 'A', psk(0x22), refresh: false); + await connector.getChannels(force: true); + expect(connector.isSyncingChannels, isFalse); + expect(getFrames(), isEmpty); + + ok(); + expect(await write, ChannelWrite.ok); + await Future.delayed(Duration.zero); + expect(connector.isSyncingChannels, isTrue); + expect(getFrames(), isNotEmpty); + }); + + test('does not start between two writes of a batch', () async { + final batch = connector.batchChannelWrites(() async { + final first = connector.setChannel(3, 'A', psk(0x22), refresh: false); + await connector.getChannels(force: true); + ok(); + await first; + await Future.delayed(Duration.zero); + // Between the two writes: the deferred sync must not have started. + expect(connector.isSyncingChannels, isFalse); + final second = connector.setChannel(4, 'B', psk(0x33), refresh: false); + ok(); + return second; + }); + + expect(await batch, ChannelWrite.ok); + expect(getFrames(), isNotEmpty, reason: 'runs once the batch ends'); + }); }); // #1024: after a FAILED sync the cached list is restored but diff --git a/test/helpers/channel_slot_ui_test.dart b/test/helpers/channel_slot_ui_test.dart index 7fa56c2c..a1b566dd 100644 --- a/test/helpers/channel_slot_ui_test.dart +++ b/test/helpers/channel_slot_ui_test.dart @@ -43,6 +43,7 @@ final _allMessages = [ _l10n.channels_writeOccupied, _l10n.channels_writeRejected, _l10n.channels_writeNoReply, + _l10n.channels_writeClearedNotAdded, ]; Future _host(WidgetTester tester) async { @@ -147,6 +148,7 @@ void main() { ChannelWrite.occupied: _l10n.channels_writeOccupied, ChannelWrite.rejected: _l10n.channels_writeRejected, ChannelWrite.noReply: _l10n.channels_writeNoReply, + ChannelWrite.clearedNotAdded: _l10n.channels_writeClearedNotAdded, }; for (final entry in cases.entries) { testWidgets('${entry.key.name}: explained, persistently', (tester) async { diff --git a/untranslated.json b/untranslated.json index 8d5234e7..3e152471 100644 --- a/untranslated.json +++ b/untranslated.json @@ -160,6 +160,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -536,6 +537,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -912,6 +914,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -1288,6 +1291,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -1664,6 +1668,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2040,6 +2045,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2416,6 +2422,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2792,6 +2799,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3168,6 +3176,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3544,6 +3553,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3920,6 +3930,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -4296,6 +4307,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -4672,6 +4684,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -5048,6 +5061,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -5424,6 +5438,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -5800,6 +5815,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -6176,6 +6192,7 @@ "channels_writeOccupied", "channels_writeRejected", "channels_writeNoReply", + "channels_writeClearedNotAdded", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", From 5d563906c6a1f0a2029acad5cfc127ace8b1ed22 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Sat, 7 Nov 2026 04:40:06 -0500 Subject: [PATCH 7/7] fix(#1025): a channel write never starts its own re-read Second Gemini round on Epic #1021, findings verified against the code. Kept, fixed: - A writer's re-read called _syncChannels directly, so with two writes overlapping, the first to finish started a sync while the second still waited on the same reply queue. The trigger was restoreChannelsToRadio, the one write path the UI did not gate. Writers now only request the re-read; the last write to finish runs it, once. Nested writes (an edit's clear and add) and batches re-read once, at the end. - Restore to radio refuses with the busy message while the table is busy, like every other channel write. With that, no write path can overlap a sync. Justified, not changed: - "A write slips in between a batch ending and its deferred sync starting": calling an async function runs synchronously up to its first await, and _syncChannels sets _isSyncingChannels before any await, so no tap can land in between. - "A disconnect leaves the write counter stuck": every write decrements in finally, and _writeChannelSlot returns within the 5 s reply timeout even after the queue is cleared. A sync deferred meanwhile runs when that write ends. - "A deferred sync is dropped if a sync is already running": reachable only when a write overlaps a running sync, which no write path allows now. Mutation-checked: a writer starting its own re-read fails the new overlapping-writes test. Full suite 1963 pass, analyze clean. Co-Authored-By: Claude Opus 5.5 --- lib/connector/meshcore_connector.dart | 17 +++++++++++------ lib/screens/channels_screen.dart | 4 ++++ test/connector/channel_write_reply_test.dart | 15 +++++++++++++++ 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index ac985edb..fa6ff098 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -7282,8 +7282,13 @@ class MeshCoreConnector extends ChangeNotifier { void _beginChannelWrite() => _channelWritesInFlight++; - /// Ends one write; the last one to end runs any sync that [getChannels] - /// deferred while writes were waiting for their replies. + /// Asks for a re-read once every channel write has its answer. A writer + /// never starts one itself: another write may still be waiting on the same + /// reply queue. Nested and batched writes therefore re-read once, at the end. + void _syncAfterChannelWrites() => _channelSyncDeferredByWrite = true; + + /// Ends one write; the last one to end runs the sync requested by a writer, + /// or by [getChannels] while writes were waiting for their replies. void _endChannelWrite() { _channelWritesInFlight--; if (_channelWritesInFlight == 0 && _channelSyncDeferredByWrite) { @@ -7360,7 +7365,7 @@ class MeshCoreConnector extends ChangeNotifier { // the radio has not answered for yet and report 0 every time. The // authoritative feedback is the erased-slot banner, which is re-derived // on every sync and therefore stays up if some writes did not land. - await _syncChannels(force: true); + _syncAfterChannelWrites(); return sent; } finally { _endChannelWrite(); @@ -7419,7 +7424,7 @@ class MeshCoreConnector extends ChangeNotifier { try { final cleared = await _writeChannelSlot(channel.index, '', Uint8List(16)); if (cleared != ChannelWrite.ok) { - await _syncChannels(force: true); + _syncAfterChannelWrites(); return cleared; } await _retireSlotOccupant(channel.index); @@ -7450,7 +7455,7 @@ class MeshCoreConnector extends ChangeNotifier { await _channelMessageStore.clearChannelMessages(index); _channelMessages.remove(index); } - if (refresh) await _syncChannels(force: true); + if (refresh) _syncAfterChannelWrites(); return result; } finally { _endChannelWrite(); @@ -7480,7 +7485,7 @@ class MeshCoreConnector extends ChangeNotifier { // Re-read on every outcome: after a refusal the list we chose the slot // from was wrong, and after no reply nobody knows what the slot holds. - if (refresh) await _syncChannels(force: true); + if (refresh) _syncAfterChannelWrites(); return result; } finally { _endChannelWrite(); diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index a49b2046..cb2d8958 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -1871,6 +1871,10 @@ class _ChannelsScreenState extends State ), ); if (confirmed != true) return; + // Its writes share the reply queue with any sync or other channel write, + // so like every channel write it waits for a quiet table (#1026). + if (!context.mounted) return; + if (refuseWhileChannelTableBusy(context, connector)) return; final written = await connector.restoreChannelsToRadio(); if (!context.mounted) return; diff --git a/test/connector/channel_write_reply_test.dart b/test/connector/channel_write_reply_test.dart index 4cda5921..2ba161af 100644 --- a/test/connector/channel_write_reply_test.dart +++ b/test/connector/channel_write_reply_test.dart @@ -259,6 +259,21 @@ void main() { expect(await batch, ChannelWrite.ok); expect(getFrames(), isNotEmpty, reason: 'runs once the batch ends'); }); + + test('a write\'s own re-read waits for another pending write', () async { + final first = connector.setChannel(3, 'A', psk(0x22)); + final second = connector.deleteChannel(4); + + ok(); // answers the first; the second is still waiting + expect(await first, ChannelWrite.ok); + await Future.delayed(Duration.zero); + expect(connector.isSyncingChannels, isFalse); + expect(getFrames(), isEmpty); + + ok(); + expect(await second, ChannelWrite.ok); + expect(connector.isSyncingChannels, isTrue); + }); }); // #1024: after a FAILED sync the cached list is restored but