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] 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",