diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index e49c129c..18f57607 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -5355,6 +5355,33 @@ class MeshCoreConnector extends ChangeNotifier { // Apply ordering and notify UI _applyChannelOrder(); notifyListeners(); + + // #839: one-time migration of the pre-per-radio notify state into THIS + // radio (the first synced after upgrade). The service guards itself with a + // persisted flag, so this is a no-op on every later sync and later radio. + _migrateLegacyChannelNotifyForThisRadio(); + } + + void _migrateLegacyChannelNotifyForThisRadio() { + final service = _appSettingsService; + if (service == null || service.settings.channelNotifyMigrated) return; + final prefix = selfPublicKeyHex; + if (prefix.isEmpty || _channels.isEmpty) return; + final pskByIndex = {}; + final pskByName = {}; + for (final channel in _channels) { + final psk = channel.pskHex; + if (psk.isEmpty) continue; + pskByIndex[channel.index] = psk; + pskByName[channel.name] = psk; + } + unawaited( + service.migrateLegacyChannelNotify( + devicePrefix: prefix, + pskByChannelIndex: pskByIndex, + pskByChannelName: pskByName, + ), + ); } void _cleanupChannelSync({required bool completed}) { @@ -8123,11 +8150,8 @@ class MeshCoreConnector extends ChangeNotifier { // the setting survives a rename and does not follow a reused slot (#259). // Evaluated against resolvedText so a translated mention still matches. final mode = _appSettingsService!.channelNotifyMode( - identityKey: AppSettings.channelNotifyKey( - channelIndex: channelIndex, - pskHex: _findChannelByIndex(channelIndex)?.pskHex, - ), - channelName: label, + devicePrefix: selfPublicKeyHex, + pskHex: _findChannelByIndex(channelIndex)?.pskHex, ); switch (mode) { case ChannelNotifyMode.off: diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 7e95baa1..44b7983b 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -158,11 +158,24 @@ class AppSettings { /// written, so an older build can be rolled back to without losing mutes. final Set mutedChannels; - /// Per-channel notification level, keyed by [channelNotifyKey], the PSK - /// identity when known, else the slot index. Keying by PSK (not by display - /// name, and not by slot) means the setting survives a rename and does not - /// bleed across a slot reassignment (#193/#194). + /// Legacy flat per-channel notify map (pre-#839), keyed by `psk_` or a + /// bare slot index, with no per-radio scoping. Superseded by + /// [channelNotifyModesByRadio]. Retained only as migration input and for + /// rollback; never consulted by the live resolution. See #839. final Map channelNotifyModes; + + /// Per-radio per-channel notify level: device-key prefix (first 10 hex of the + /// connected radio's public key, like every other per-radio store) -> channel + /// PSK hex -> mode. Keyed by PSK within a radio so it survives a rename and + /// does not follow a reused slot (#193/#194); scoped by radio so one radio's + /// settings never bleed into another, and there is no bare-index fallback that + /// could (#839). `all` is the default and is never stored. + final Map> channelNotifyModesByRadio; + + /// One-time guard: true once the legacy flat map / mute set has been migrated + /// into [channelNotifyModesByRadio] for the first radio seen post-upgrade, so + /// a second radio does not inherit the ambiguous legacy state (#839). + final bool channelNotifyMigrated; final bool mapShowDiscoveryContacts; final String tcpServerAddress; final int tcpServerPort; @@ -185,17 +198,6 @@ class AppSettings { return profile.charMap; } - /// Storage key for a channel's notify mode. - /// - /// Mirrors the identity scheme [ChannelMessageStore] uses for history (#194): - /// the PSK hex when the channel is synced and its key is known, else the slot - /// index as a fallback. The `psk_` marker keeps the two spaces from colliding - /// (a PSK is 32 hex chars; an index is a small integer). - static String channelNotifyKey({required int channelIndex, String? pskHex}) { - if (pskHex != null && pskHex.isNotEmpty) return 'psk_$pskHex'; - return '$channelIndex'; - } - AppSettings({ this.clearPathOnMaxRetry = false, this.mapShowRepeaters = true, @@ -234,6 +236,8 @@ class AppSettings { this.unitSystem = UnitSystem.metric, Set? mutedChannels, Map? channelNotifyModes, + Map>? channelNotifyModesByRadio, + this.channelNotifyMigrated = false, this.mapShowDiscoveryContacts = true, this.tcpServerAddress = '', this.tcpServerPort = 0, @@ -251,6 +255,7 @@ class AppSettings { batteryChemistryByRepeaterId = batteryChemistryByRepeaterId ?? {}, mutedChannels = mutedChannels ?? {}, channelNotifyModes = channelNotifyModes ?? {}, + channelNotifyModesByRadio = channelNotifyModesByRadio ?? {}, translationDownloadedModels = translationDownloadedModels ?? const [], cyr2latProfiles = cyr2latProfiles ?? @@ -304,6 +309,13 @@ class AppSettings { 'channel_notify_modes': channelNotifyModes.map( (key, mode) => MapEntry(key, mode.value), ), + 'channel_notify_modes_by_radio': channelNotifyModesByRadio.map( + (prefix, modes) => MapEntry( + prefix, + modes.map((psk, mode) => MapEntry(psk, mode.value)), + ), + ), + 'channel_notify_migrated': channelNotifyMigrated, 'map_show_discovery_contacts': mapShowDiscoveryContacts, 'tcp_server_address': tcpServerAddress, 'tcp_server_port': tcpServerPort, @@ -423,6 +435,19 @@ class AppSettings { MapEntry(key.toString(), parseChannelNotifyMode(value)), ) ?? {}, + channelNotifyModesByRadio: + (json['channel_notify_modes_by_radio'] as Map?)?.map( + (prefix, modes) => MapEntry( + prefix.toString(), + (modes as Map?)?.map( + (psk, value) => + MapEntry(psk.toString(), parseChannelNotifyMode(value)), + ) ?? + {}, + ), + ) ?? + {}, + channelNotifyMigrated: json['channel_notify_migrated'] as bool? ?? false, mapShowDiscoveryContacts: json['map_show_discovery_contacts'] as bool? ?? true, tcpServerAddress: json['tcp_server_address'] as String? ?? '', @@ -521,6 +546,8 @@ class AppSettings { UnitSystem? unitSystem, Set? mutedChannels, Map? channelNotifyModes, + Map>? channelNotifyModesByRadio, + bool? channelNotifyMigrated, bool? mapShowDiscoveryContacts, String? tcpServerAddress, int? tcpServerPort, @@ -585,6 +612,10 @@ class AppSettings { unitSystem: unitSystem ?? this.unitSystem, mutedChannels: mutedChannels ?? this.mutedChannels, channelNotifyModes: channelNotifyModes ?? this.channelNotifyModes, + channelNotifyModesByRadio: + channelNotifyModesByRadio ?? this.channelNotifyModesByRadio, + channelNotifyMigrated: + channelNotifyMigrated ?? this.channelNotifyMigrated, mapShowDiscoveryContacts: mapShowDiscoveryContacts ?? this.mapShowDiscoveryContacts, tcpServerAddress: tcpServerAddress ?? this.tcpServerAddress, diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index b32adad5..6fea9111 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -489,8 +489,10 @@ class _ChannelChatScreenState extends State { Icon( channelNotifyModeIcon( context.read().channelNotifyMode( - identityKey: channelNotifyKeyFor(widget.channel), - channelName: widget.channel.name, + devicePrefix: context + .read() + .selfPublicKeyHex, + pskHex: widget.channel.pskHex, ), ), size: 20, diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 3bdf221a..a308eb17 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -490,8 +490,8 @@ class _ChannelsScreenState extends State final parentContext = context; final settingsService = context.read(); final notifyMode = settingsService.channelNotifyMode( - identityKey: channelNotifyKeyFor(channel), - channelName: channel.name, + devicePrefix: connector.selfPublicKeyHex, + pskHex: channel.pskHex, ); showModalBottomSheet( diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index 8f41bf0c..21a267be 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -237,42 +237,51 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(unitSystem: value)); } - /// Per-channel notification level. - /// - /// Resolution order: the PSK-keyed mode when one is set, else the legacy - /// name-keyed mute (so a channel muted before this feature existed still - /// reports [ChannelNotifyMode.off]), else [ChannelNotifyMode.all]. - /// - /// [identityKey] comes from [AppSettings.channelNotifyKey]; the caller - /// resolves the slot index to a PSK. + /// First 10 hex of the connected radio's key, matching every other per-radio + /// store. Empty when no radio is connected -> the caller gets the default. + static String _scopePrefix(String devicePrefix) => + devicePrefix.length > 10 ? devicePrefix.substring(0, 10) : devicePrefix; + + /// Resolve a channel's notify mode for the CONNECTED radio ([devicePrefix]) + /// by its [pskHex]. No bare-index fallback and no cross-radio legacy fallback: + /// an unknown scope (no radio, or PSK not yet synced) resolves to the default + /// `all` rather than inheriting another radio's or slot's state (#839). ChannelNotifyMode channelNotifyMode({ - required String identityKey, - required String channelName, + required String devicePrefix, + required String? pskHex, }) { - final mode = _settings.channelNotifyModes[identityKey]; - if (mode != null) return mode; - if (_settings.mutedChannels.contains(channelName)) { - return ChannelNotifyMode.off; + final prefix = _scopePrefix(devicePrefix); + if (prefix.isEmpty || pskHex == null || pskHex.isEmpty) { + return ChannelNotifyMode.all; } - return ChannelNotifyMode.all; + return _settings.channelNotifyModesByRadio[prefix]?[pskHex] ?? + ChannelNotifyMode.all; } + /// Store a channel's notify mode for the connected radio. Keyed only by + /// ([devicePrefix], [pskHex]); when either is unknown this is a no-op so we + /// never write an unscoped or index-keyed entry. `all` removes the single + /// entry (it is the default), so set-and-back genuinely resets (#839). Future setChannelNotifyMode({ - required String identityKey, + required String devicePrefix, + required String? pskHex, required String channelName, required ChannelNotifyMode mode, }) async { - final modes = Map.from( - _settings.channelNotifyModes, - ); + final prefix = _scopePrefix(devicePrefix); + if (prefix.isEmpty || pskHex == null || pskHex.isEmpty) return; + + final byRadio = _copyByRadio(); + final radioModes = byRadio.putIfAbsent(prefix, () => {}); if (mode == ChannelNotifyMode.all) { - modes.remove(identityKey); // `all` is the default; don't store it. + radioModes.remove(pskHex); + if (radioModes.isEmpty) byRadio.remove(prefix); } else { - modes[identityKey] = mode; + radioModes[pskHex] = mode; } - // Keep the legacy name-keyed set in sync so rolling back to a build without - // notify modes still honours an Off channel. Remove after one release. + // Keep the legacy name-keyed set written (rollback compat only; it is not + // consulted by the resolution above). Remove after one release. final muted = Set.from(_settings.mutedChannels); if (mode == ChannelNotifyMode.off) { muted.add(channelName); @@ -281,25 +290,67 @@ class AppSettingsService extends ChangeNotifier { } await updateSettings( - _settings.copyWith(channelNotifyModes: modes, mutedChannels: muted), + _settings.copyWith( + channelNotifyModesByRadio: byRadio, + mutedChannels: muted, + ), ); } - bool isChannelMuted(String channelName) { - return _settings.mutedChannels.contains(channelName); - } + /// One-time migration of the pre-#839 global state into the FIRST radio seen + /// after upgrade. Called by the connector once that radio's channels are + /// known. Later radios start clean, so the ambiguous legacy state never + /// bleeds across radios. [pskByChannelIndex] / [pskByChannelName] resolve the + /// legacy index- and name-keyed entries to a PSK; unresolvable ones drop. + Future migrateLegacyChannelNotify({ + required String devicePrefix, + required Map pskByChannelIndex, + required Map pskByChannelName, + }) async { + if (_settings.channelNotifyMigrated) return; + final prefix = _scopePrefix(devicePrefix); + if (prefix.isEmpty) return; + + final byRadio = _copyByRadio(); + final radioModes = byRadio.putIfAbsent(prefix, () => {}); + + // 1) psk_ entries map straight across; 2) entries resolve via + // the connected radio's channel table (index entries that don't resolve are + // ambiguous and dropped); later writes override earlier. + _settings.channelNotifyModes.forEach((key, mode) { + if (mode == ChannelNotifyMode.all) return; + if (key.startsWith('psk_')) { + radioModes[key.substring(4)] = mode; + } else { + final idx = int.tryParse(key); + final psk = idx == null ? null : pskByChannelIndex[idx]; + if (psk != null && psk.isNotEmpty) radioModes[psk] = mode; + } + }); - Future muteChannel(String channelName) async { - final updated = Set.from(_settings.mutedChannels)..add(channelName); - await updateSettings(_settings.copyWith(mutedChannels: updated)); - } + // 3) legacy name-keyed mutes become Off on their resolved PSK. + for (final name in _settings.mutedChannels) { + final psk = pskByChannelName[name]; + if (psk != null && psk.isNotEmpty) { + radioModes[psk] = ChannelNotifyMode.off; + } + } - Future unmuteChannel(String channelName) async { - final updated = Set.from(_settings.mutedChannels) - ..remove(channelName); - await updateSettings(_settings.copyWith(mutedChannels: updated)); + if (radioModes.isEmpty) byRadio.remove(prefix); + + await updateSettings( + _settings.copyWith( + channelNotifyModesByRadio: byRadio, + channelNotifyMigrated: true, + ), + ); } + Map> _copyByRadio() => { + for (final e in _settings.channelNotifyModesByRadio.entries) + e.key: Map.from(e.value), + }; + Future setTcpServerAddress(String value) async { await updateSettings(_settings.copyWith(tcpServerAddress: value)); } diff --git a/lib/widgets/channel_notify_mode.dart b/lib/widgets/channel_notify_mode.dart index c87486bf..b58b13e9 100644 --- a/lib/widgets/channel_notify_mode.dart +++ b/lib/widgets/channel_notify_mode.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import '../connector/meshcore_connector.dart'; import '../l10n/l10n.dart'; import '../models/app_settings.dart'; import '../models/channel.dart'; @@ -10,13 +11,6 @@ import '../services/app_settings_service.dart'; /// Channels list and from inside a channel's chat (#275). Single implementation /// so the two entry points cannot drift. -/// Notify-mode storage key for [channel]: its PSK identity, so the setting -/// survives a rename and does not follow a reused slot (#259). -String channelNotifyKeyFor(Channel channel) => AppSettings.channelNotifyKey( - channelIndex: channel.index, - pskHex: channel.pskHex, -); - IconData channelNotifyModeIcon(ChannelNotifyMode mode) { switch (mode) { case ChannelNotifyMode.all: @@ -41,10 +35,10 @@ String channelNotifyModeLabel(BuildContext context, ChannelNotifyMode mode) { void showChannelNotifyModeDialog(BuildContext context, Channel channel) { final settingsService = context.read(); - final identityKey = channelNotifyKeyFor(channel); + final devicePrefix = context.read().selfPublicKeyHex; final current = settingsService.channelNotifyMode( - identityKey: identityKey, - channelName: channel.name, + devicePrefix: devicePrefix, + pskHex: channel.pskHex, ); showDialog( @@ -63,7 +57,8 @@ void showChannelNotifyModeDialog(BuildContext context, Channel channel) { onTap: () async { Navigator.pop(dialogContext); await settingsService.setChannelNotifyMode( - identityKey: identityKey, + devicePrefix: devicePrefix, + pskHex: channel.pskHex, channelName: channel.name, mode: mode, ); diff --git a/test/services/channel_notify_per_radio_test.dart b/test/services/channel_notify_per_radio_test.dart new file mode 100644 index 00000000..0c4ba545 --- /dev/null +++ b/test/services/channel_notify_per_radio_test.dart @@ -0,0 +1,218 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/app_settings.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +// #839: channel notify modes must be scoped per radio (connected device-key +// prefix), the bare slot-index fallback is gone, and setting All must truly +// reset. Positive AND negative cases per the owner acceptance. +void main() { + const prefixA = 'aaaaaaaaaa'; + const prefixB = 'bbbbbbbbbb'; + const pskX = '0123456789abcdef0123456789abcdef'; + const pskPublic = 'ffffffffffffffffffffffffffffffff'; + + AppSettingsService service() => AppSettingsService(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + test('a mode set on radio A does not bleed into radio B', () async { + final s = service(); + await s.loadSettings(); + + await s.setChannelNotifyMode( + devicePrefix: prefixA, + pskHex: pskX, + channelName: 'Test', + mode: ChannelNotifyMode.off, + ); + + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: pskX), + ChannelNotifyMode.off, + ); + // Same channel PSK, different radio: independent, defaults to All. + expect( + s.channelNotifyMode(devicePrefix: prefixB, pskHex: pskX), + ChannelNotifyMode.all, + ); + }); + + test('set-and-back to All truly resets (no stale alias wins)', () async { + final s = service(); + await s.loadSettings(); + + await s.setChannelNotifyMode( + devicePrefix: prefixA, + pskHex: pskX, + channelName: 'Test', + mode: ChannelNotifyMode.off, + ); + await s.setChannelNotifyMode( + devicePrefix: prefixA, + pskHex: pskX, + channelName: 'Test', + mode: ChannelNotifyMode.all, + ); + + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: pskX), + ChannelNotifyMode.all, + ); + // All is the default and is not stored. + expect( + s.settings.channelNotifyModesByRadio[prefixA]?.containsKey(pskX) ?? false, + isFalse, + ); + }); + + test( + 'unknown scope resolves All and persists nothing (no index fallback)', + () async { + final s = service(); + await s.loadSettings(); + + // PSK not yet known (pre-sync): resolve All, never key by slot index. + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: null), + ChannelNotifyMode.all, + ); + expect( + s.channelNotifyMode(devicePrefix: '', pskHex: pskX), + ChannelNotifyMode.all, + ); + + // Setting with no PSK is a no-op, not an index-keyed write. + await s.setChannelNotifyMode( + devicePrefix: prefixA, + pskHex: null, + channelName: 'Test', + mode: ChannelNotifyMode.off, + ); + expect( + s.settings.channelNotifyModesByRadio[prefixA] ?? const {}, + isEmpty, + ); + }, + ); + + test('the mode survives an app restart (reload from prefs)', () async { + final s1 = service(); + await s1.loadSettings(); + await s1.setChannelNotifyMode( + devicePrefix: prefixA, + pskHex: pskX, + channelName: 'Test', + mode: ChannelNotifyMode.mentionsOnly, + ); + + // New service instance, same backing prefs = an app restart. + final s2 = service(); + await s2.loadSettings(); + expect( + s2.channelNotifyMode(devicePrefix: prefixA, pskHex: pskX), + ChannelNotifyMode.mentionsOnly, + ); + }); + + test('nested notify map round-trips through JSON', () { + final original = AppSettings( + channelNotifyModesByRadio: { + prefixA: {pskX: ChannelNotifyMode.off}, + prefixB: {pskPublic: ChannelNotifyMode.mentionsOnly}, + }, + ); + final restored = AppSettings.fromJson( + jsonDecode(jsonEncode(original.toJson())) as Map, + ); + expect( + restored.channelNotifyModesByRadio[prefixA]?[pskX], + ChannelNotifyMode.off, + ); + expect( + restored.channelNotifyModesByRadio[prefixB]?[pskPublic], + ChannelNotifyMode.mentionsOnly, + ); + }); + + test( + 'legacy flat map (psk- and index-keyed) migrates into the first radio', + () async { + // Seed the pre-#839 shape: a global flat map with a psk-keyed and an + // index-keyed entry, no nested map, not yet migrated. + final legacy = AppSettings( + channelNotifyModes: { + 'psk_$pskX': ChannelNotifyMode.mentionsOnly, + '2': ChannelNotifyMode.off, // resolvable index entry + }, + ); + SharedPreferences.setMockInitialValues({ + 'app_settings': jsonEncode(legacy.toJson()), + }); + PrefsManager.reset(); + await PrefsManager.initialize(); + + final s = service(); + await s.loadSettings(); + + // First radio connects and its channels are known: migrate into prefixA. + await s.migrateLegacyChannelNotify( + devicePrefix: prefixA, + pskByChannelIndex: {2: pskPublic}, + pskByChannelName: const {}, + ); + + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: pskX), + ChannelNotifyMode.mentionsOnly, // from the psk_ entry + ); + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: pskPublic), + ChannelNotifyMode.off, // index '2' resolved to pskPublic + ); + + // A second radio starts clean: the legacy state is not re-applied. + await s.migrateLegacyChannelNotify( + devicePrefix: prefixB, + pskByChannelIndex: {2: pskPublic}, + pskByChannelName: const {}, + ); + expect( + s.settings.channelNotifyModesByRadio[prefixB] ?? const {}, + isEmpty, + ); + }, + ); + + test( + 'legacy name-keyed mute set migrates to Off on its resolved PSK', + () async { + final legacy = AppSettings(mutedChannels: {'Public'}); + SharedPreferences.setMockInitialValues({ + 'app_settings': jsonEncode(legacy.toJson()), + }); + PrefsManager.reset(); + await PrefsManager.initialize(); + + final s = service(); + await s.loadSettings(); + await s.migrateLegacyChannelNotify( + devicePrefix: prefixA, + pskByChannelIndex: const {}, + pskByChannelName: {'Public': pskPublic}, + ); + + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: pskPublic), + ChannelNotifyMode.off, + ); + }, + ); +}