From 3a0ad8f2732b02d2b4429a7ce480646f11ef15cd Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 20 Oct 2026 01:54:11 -0400 Subject: [PATCH] feat(#750): separate what a node calls itself from what the user calls it Task 750.1 of the contact-naming plan: model and storage. Stock MeshCore has a per-node CUSTOM NAME field and keeps the original underneath; Offband could not rename a contact at all. Contact gains receivedName (the name the mesh gave us, wire and storage) and customName (the user's label, client-side only). name becomes a getter returning customName ?? receivedName, so all 85 existing display reads stay correct and a future read cannot forget. Empty and whitespace-only custom names count as unset at both the getter and the store, so clearing the field cannot leave a contact blank with no way back. The constructor and copyWith take receivedName, which made the rename a compile error at every write site. The compiler enumerated 23 of them across 5 lib files and 11 test files; none was found by reading. The advert handler is the one that matters: receivedName now updates while customName is untouched, so an advert improves accuracy without moving what the user sees. That was the defect making a client-held name impossible. customName is deliberately NOT in contact_store. That record is rebuilt from radio contact-sync data where no custom name exists, so a save after a sync would wipe it. It lives in contact_settings_store keyed by pubkey hex, which a sync cannot reach. Both stores persist receivedName, never the getter. The plan's correction on #750 found that persisting the getter is one-way data loss: the custom name would be read back as the received name and the real one destroyed with no advert able to restore it. The ?? 'Unknown' fallback is kept with a comment, since the rename is exactly the edit that drops a trailing fallback and would crash the load for a legacy row. 19 tests, positive and negative. T31 and T32 were falsified before being trusted: breaking the persist and the fallback made exactly those two fail and nothing else. Gates: analyze --fatal-infos --fatal-warnings clean, dart format 0-changed, 1305 tests passed. Co-Authored-By: Claude Opus 5 --- lib/connector/meshcore_connector.dart | 23 ++- lib/models/contact.dart | 62 ++++++- lib/screens/path_trace_map.dart | 5 +- lib/storage/contact_discovery_store.dart | 9 +- lib/storage/contact_settings_store.dart | 44 +++++ lib/storage/contact_store.dart | 17 +- .../channel_sender_resolution_test.dart | 2 +- test/connector/contact_sync_test.dart | 2 +- test/connector/region_connector_test.dart | 2 +- test/helpers/path_helper_test.dart | 2 +- test/l10n/contact_localization_test.dart | 2 +- test/models/contact_naming_test.dart | 101 ++++++++++ test/models/contact_share_uri_test.dart | 4 +- test/models/path_selection_test.dart | 2 +- .../screens/discover_regions_screen_test.dart | 2 +- test/services/path_history_service_test.dart | 2 +- .../repeater_command_service_test.dart | 2 +- test/services/retry_and_protocol_test.dart | 2 +- .../stock_config_export_service_test.dart | 2 +- test/storage/contact_naming_storage_test.dart | 172 ++++++++++++++++++ test/storage/contact_store_test.dart | 2 +- .../contact_verification_badge_test.dart | 2 +- 22 files changed, 428 insertions(+), 35 deletions(-) create mode 100644 test/models/contact_naming_test.dart create mode 100644 test/storage/contact_naming_storage_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index f1c3c21c..e9480a23 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -5120,7 +5120,9 @@ class MeshCoreConnector extends ChangeNotifier { if (index >= 0) { _contacts[index] = _contacts[index].copyWith( type: latestContact.type, - name: latestContact.name, + // Received, not `.name`: copying the getter would move one contact's + // custom name onto another's received field. (#750) + receivedName: latestContact.receivedName, pathLength: latestContact.pathLength, path: latestContact.path, flags: updatedFlags, @@ -5659,7 +5661,7 @@ class MeshCoreConnector extends ChangeNotifier { _handleContactAdvert( Contact( publicKey: contact.publicKey, - name: contact.name, + receivedName: contact.receivedName, type: contact.type, pathLength: contact.pathLength, path: contact.path, @@ -10399,7 +10401,7 @@ class MeshCoreConnector extends ChangeNotifier { Contact( rawPacket: frame, publicKey: publicKey, - name: name, + receivedName: name, type: type, pathLength: pathBytes.isEmpty ? -1 : pathBytes.length, path: Uint8List.fromList( @@ -10483,7 +10485,7 @@ class MeshCoreConnector extends ChangeNotifier { final newContact = Contact( rawPacket: rawPacket, publicKey: publicKey, - name: name, + receivedName: name, type: type, pathLength: path.length, path: Uint8List.fromList( @@ -10532,7 +10534,14 @@ class MeshCoreConnector extends ChangeNotifier { _contacts[existingIndex] = existing.copyWith( latitude: hasLocation ? latitude : existing.latitude, longitude: hasLocation ? longitude : existing.longitude, - name: hasName ? name : existing.name, + // The received name updates; the user's custom name is untouched, so + // what they see does not move. This is the whole point of #750: before + // it, an advert took the user's chosen name back every time, which is + // why the client could never hold one. `copyWith` leaves `customName` + // alone unless `clearCustomName` is passed, so nothing else is needed + // here. A nameless advert (`hasName` false) must not blank the + // received name either. (T15, T16, T18, T19) + receivedName: hasName ? name : existing.receivedName, path: Uint8List.fromList(path.reversed.toList()), pathLength: path.length, lastMessageAt: mergedLastMessageAt, @@ -10624,7 +10633,7 @@ class MeshCoreConnector extends ChangeNotifier { _discoveredContacts[existingIndex] = _discoveredContacts[existingIndex] .copyWith( rawPacket: rawPacket, - name: contact.name, + receivedName: contact.receivedName, type: contact.type, pathLength: contact.pathLength, path: contact.path, @@ -10642,7 +10651,7 @@ class MeshCoreConnector extends ChangeNotifier { final disContact = Contact( rawPacket: rawPacket, publicKey: contact.publicKey, - name: contact.name, + receivedName: contact.receivedName, type: contact.type, pathLength: contact.pathLength, path: contact.path, diff --git a/lib/models/contact.dart b/lib/models/contact.dart index f4d1dc6b..50f67bd2 100644 --- a/lib/models/contact.dart +++ b/lib/models/contact.dart @@ -5,7 +5,40 @@ import '../connector/meshcore_protocol.dart'; class Contact { final Uint8List publicKey; - final String name; + + /// The name this node last gave us, from its own signed advert or from an + /// unsigned contact-share card. Never the user's label. (#750) + /// + /// Called "received" rather than "advert" deliberately: a contact-share card + /// is plain unsigned channel text, so a card-added contact carries a name here + /// that was never advertised by anyone. Whether a signed advert has ever been + /// seen is a separate question, answered by [isAdvertVerified]. + /// + /// **This is what goes on the wire and into storage.** Read [name] to display. + /// Sending [name] to the radio would overwrite the shared record of what the + /// node calls itself with one user's private label. + final String receivedName; + + /// The user's own label for this node, or null when they have not set one. + /// + /// Client-side only. Firmware holds a single `char name[32]` per contact + /// (`ContactInfo.h:10`) and has no override concept, so this can never be sent + /// to the radio. Stock MeshCore's CUSTOM NAME field works the same way. + final String? customName; + + /// What to show the user: their own label if they set one, otherwise the name + /// the node gave us. + /// + /// Every display site reads this, which is why it keeps the short name: an + /// existing or future read of `.name` is already correct and cannot forget. + /// An empty or whitespace-only custom name counts as unset, so clearing the + /// text field cannot leave a contact with a blank name and no way back. + String get name { + final custom = customName; + if (custom == null || custom.trim().isEmpty) return receivedName; + return custom; + } + final int type; final int flags; @@ -38,7 +71,8 @@ class Contact { Contact({ required this.publicKey, - required this.name, + required this.receivedName, + this.customName, required this.type, this.flags = 0, required this.pathLength, @@ -91,7 +125,13 @@ class Contact { Contact copyWith({ Uint8List? publicKey, - String? name, + String? receivedName, + String? customName, + + /// Clears the user's label so [name] falls back to [receivedName]. A null + /// `customName` means "leave it alone", the same as every other field here, + /// so removing one needs its own flag. (#750) + bool clearCustomName = false, int? type, int? flags, int? pathLength, @@ -110,7 +150,8 @@ class Contact { }) { return Contact( publicKey: publicKey ?? this.publicKey, - name: name ?? this.name, + receivedName: receivedName ?? this.receivedName, + customName: clearCustomName ? null : (customName ?? this.customName), type: type ?? this.type, flags: flags ?? this.flags, pathLength: pathLength ?? this.pathLength, @@ -238,7 +279,8 @@ class Contact { return Contact( publicKey: pubKey, - name: name.isEmpty ? 'Unknown' : name, + // Straight off the wire, so a received name by definition. (#750) + receivedName: name.isEmpty ? 'Unknown' : name, type: type, flags: flags, pathLength: @@ -378,7 +420,10 @@ class Contact { return Contact( publicKey: publicKey, - name: name.isEmpty ? 'Unknown' : name, + // A contact-share card is unsigned channel text, so this name was chosen + // by whoever posted the card and may not be the key holder. Received, not + // the user's label, and not advertised either. (#750, #645) + receivedName: name.isEmpty ? 'Unknown' : name, type: type, flags: 0, pathLength: -1, @@ -440,8 +485,9 @@ class Contact { return Contact( publicKey: publicKey, - // Matches fromFrame's convention for a nameless contact. - name: (name == null || name.isEmpty) ? 'Unknown' : name, + // Matches fromFrame's convention for a nameless contact. Received: the + // URI's author picked this name, the same as a card. (#750) + receivedName: (name == null || name.isEmpty) ? 'Unknown' : name, type: type, flags: 0, // Flood until the mesh teaches us a path. Mirrors the firmware's diff --git a/lib/screens/path_trace_map.dart b/lib/screens/path_trace_map.dart index a4dc3fb6..32bc4fee 100644 --- a/lib/screens/path_trace_map.dart +++ b/lib/screens/path_trace_map.dart @@ -378,7 +378,10 @@ class _PathTraceMapScreenState extends State { path: Uint8List(0), pathLength: 0, publicKey: connector.selfPublicKey ?? Uint8List(0), - name: context.l10n.pathTrace_you, + // A synthetic tile for this device, not a real contact. There is no + // user label to override, so the localized "You" is the received name + // and `.name` returns it unchanged. (#750) + receivedName: context.l10n.pathTrace_you, type: advTypeChat, latitude: connector.selfLatitude, longitude: connector.selfLongitude, diff --git a/lib/storage/contact_discovery_store.dart b/lib/storage/contact_discovery_store.dart index b2827572..1e8d9971 100644 --- a/lib/storage/contact_discovery_store.dart +++ b/lib/storage/contact_discovery_store.dart @@ -52,7 +52,11 @@ class ContactDiscoveryStore { Map _toJson(Contact contact) { return { 'publicKey': base64Encode(contact.publicKey), - 'name': contact.name, + // The RECEIVED name, never `contact.name`. Same one-way data loss as + // `contact_store`: the getter would persist a user label into this key + // and the next load would read it back as what the node calls itself. + // (#750) + 'name': contact.receivedName, 'type': contact.type, 'flags': contact.flags, 'pathLength': contact.pathLength, @@ -78,7 +82,8 @@ class ContactDiscoveryStore { final lastModifiedMs = json['lastModified'] as int?; return Contact( publicKey: Uint8List.fromList(base64Decode(json['publicKey'] as String)), - name: json['name'] as String? ?? 'Unknown', + // Fallback retained for the same reason as `contact_store`. (T31) + receivedName: json['name'] as String? ?? 'Unknown', type: json['type'] as int? ?? 0, flags: json['flags'] as int? ?? 0, pathLength: json['pathLength'] as int? ?? -1, diff --git a/lib/storage/contact_settings_store.dart b/lib/storage/contact_settings_store.dart index 17832586..7bc427ee 100644 --- a/lib/storage/contact_settings_store.dart +++ b/lib/storage/contact_settings_store.dart @@ -4,12 +4,56 @@ import 'prefs_manager.dart'; class ContactSettingsStore { static const String _cyr2latKeyPrefix = 'contact_cyr2lat_'; + /// Per-contact custom display name, the user's own label. (#750) + /// + /// This lives here rather than in `contact_store` on purpose. That record is + /// rebuilt from the radio's contact-sync data, where no custom name exists, + /// so a save after a sync would wipe it. Keyed by pubkey hex here, a sync + /// cannot reach it. + static const String _customNameKeyPrefix = 'contact_customname_'; + String publicKeyHex = ''; set setPublicKeyHex(String value) => publicKeyHex = value.length > 10 ? value.substring(0, 10) : ''; String get keyForCyr2Lat => '$_cyr2latKeyPrefix$publicKeyHex'; + String get keyForCustomName => '$_customNameKeyPrefix$publicKeyHex'; + + /// The user's label for [contactKeyHex], or null when they have not set one. + Future loadCustomName(String contactKeyHex) async { + if (publicKeyHex.isEmpty) { + appLogger.warn( + 'Public key hex is not set. Cannot load contact custom name.', + ); + return null; + } + final prefs = PrefsManager.instance; + return prefs.getString('$keyForCustomName$contactKeyHex'); + } + + /// Sets or clears the user's label for [contactKeyHex]. + /// + /// Null, empty and whitespace-only all **remove** the entry rather than + /// storing a blank. This is the second enforcement point for that rule, after + /// `Contact.name`: a UI that passes an empty string cannot leave a contact + /// with a blank display name and no way back. (T9d, T9e, T29, T30) + Future saveCustomName(String contactKeyHex, String? name) async { + if (publicKeyHex.isEmpty) { + appLogger.warn( + 'Public key hex is not set. Cannot save contact custom name.', + ); + return; + } + final prefs = PrefsManager.instance; + final key = '$keyForCustomName$contactKeyHex'; + if (name == null || name.trim().isEmpty) { + await prefs.remove(key); + } else { + await prefs.setString(key, name); + } + } + Future loadCyr2LatEnabled(String contactKeyHex) async { if (publicKeyHex.isEmpty) { appLogger.warn( diff --git a/lib/storage/contact_store.dart b/lib/storage/contact_store.dart index 9a647864..d478dd22 100644 --- a/lib/storage/contact_store.dart +++ b/lib/storage/contact_store.dart @@ -104,7 +104,17 @@ class ContactStore { Map _toJson(Contact contact) { return { 'publicKey': base64Encode(contact.publicKey), - 'name': contact.name, + // The RECEIVED name, never `contact.name`. Reading the getter here would + // write the user's custom name into this key, and the next load would + // read it back as the received name. The real name the node gave us + // would be destroyed permanently, with no advert able to restore it, + // because the contact would already appear to have that name. (#750) + // + // `customName` is deliberately NOT stored here. This record is rebuilt + // from radio contact-sync data, where no custom name exists, so a save + // after a sync would wipe it. It lives in `contact_settings_store`, + // keyed by pubkey hex, which a sync cannot reach. + 'name': contact.receivedName, 'type': contact.type, 'flags': contact.flags, 'pathLength': contact.pathLength, @@ -142,7 +152,10 @@ class ContactStore { } return Contact( publicKey: Uint8List.fromList(base64Decode(json['publicKey'] as String)), - name: json['name'] as String? ?? 'Unknown', + // Keep the `?? 'Unknown'`: a legacy row can carry a null or missing name, + // and `receivedName` is non-nullable, so dropping this fallback during + // the rename would crash the load for anyone holding such a row. (T31) + receivedName: json['name'] as String? ?? 'Unknown', type: json['type'] as int? ?? 0, flags: json['flags'] as int? ?? 0, // Records written before #309 have no 'pathHashWidth' and their path was diff --git a/test/connector/channel_sender_resolution_test.dart b/test/connector/channel_sender_resolution_test.dart index b5213a76..4e6182c0 100644 --- a/test/connector/channel_sender_resolution_test.dart +++ b/test/connector/channel_sender_resolution_test.dart @@ -11,7 +11,7 @@ import 'package:meshcore_open/models/contact.dart'; /// namesake case the UI must never resolve on the user's behalf. Contact _contact(String name, int keyByte, {int type = advTypeChat}) => Contact( publicKey: Uint8List.fromList(List.filled(32, keyByte)), - name: name, + receivedName: name, type: type, pathLength: -1, path: Uint8List(0), diff --git a/test/connector/contact_sync_test.dart b/test/connector/contact_sync_test.dart index 8752e3f6..793b95ce 100644 --- a/test/connector/contact_sync_test.dart +++ b/test/connector/contact_sync_test.dart @@ -44,7 +44,7 @@ Uint8List get _end => Uint8List.fromList([respCodeEndOfContacts, ..._u32(0)]); Contact _saved(int keyByte, String name) => Contact( publicKey: Uint8List.fromList(List.filled(32, keyByte)), - name: name, + receivedName: name, type: advTypeChat, pathLength: -1, path: Uint8List(0), diff --git a/test/connector/region_connector_test.dart b/test/connector/region_connector_test.dart index 9480d43f..b565fc17 100644 --- a/test/connector/region_connector_test.dart +++ b/test/connector/region_connector_test.dart @@ -126,7 +126,7 @@ void main() { connector.contactsForTest.add( Contact( publicKey: pk, - name: 'rpt', + receivedName: 'rpt', type: advTypeRepeater, pathLength: 2, pathHashWidth: 1, diff --git a/test/helpers/path_helper_test.dart b/test/helpers/path_helper_test.dart index 1329ef4f..8a3b291c 100644 --- a/test/helpers/path_helper_test.dart +++ b/test/helpers/path_helper_test.dart @@ -16,7 +16,7 @@ Contact _contact({ } return Contact( publicKey: key, - name: name, + receivedName: name, type: type, pathLength: 0, path: Uint8List(0), diff --git a/test/l10n/contact_localization_test.dart b/test/l10n/contact_localization_test.dart index 62f8b6c8..b00bc35e 100644 --- a/test/l10n/contact_localization_test.dart +++ b/test/l10n/contact_localization_test.dart @@ -14,7 +14,7 @@ Contact _contact({ }) { return Contact( publicKey: Uint8List.fromList(List.generate(32, (i) => i + 1)), - name: 'Node', + receivedName: 'Node', type: type, pathLength: pathLength, path: Uint8List(0), diff --git a/test/models/contact_naming_test.dart b/test/models/contact_naming_test.dart new file mode 100644 index 00000000..00ea63fa --- /dev/null +++ b/test/models/contact_naming_test.dart @@ -0,0 +1,101 @@ +// Custom Name override for contacts (#750), model half. +// +// `Contact.name` becomes a getter returning `customName ?? receivedName`, so +// the 85 existing display reads stay correct and untouched while every write +// site is forced to say which name it means. +// +// Tests T1 to T8 and T31 from the plan of record, +// docs/initiatives/standalone/750-contact-naming/PLAN.md. +// +// The negatives here are the ones that matter. A positive-only suite would keep +// passing while an advert quietly took the user's chosen name back. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/contact.dart'; + +Contact _contact({required String receivedName, String? customName}) => Contact( + publicKey: Uint8List.fromList(List.filled(32, 0x11)), + receivedName: receivedName, + customName: customName, + type: 1, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.utc(2026, 7, 1), +); + +void main() { + group('Contact.name resolution (#750)', () { + test('T1 + returns the custom name when one is set', () { + final c = _contact(receivedName: 'KQ4EZN-Repeater', customName: 'Chuck'); + + expect(c.name, 'Chuck'); + }); + + test('T2 - falls back to the received name, and does not invent one', () { + final c = _contact(receivedName: 'KQ4EZN-Repeater'); + + expect(c.name, 'KQ4EZN-Repeater'); + expect(c.customName, isNull); + }); + + test('T3 - an empty custom name counts as unset, not as a blank name', () { + // Otherwise a user who clears the field by deleting its text gets a blank + // display name with no way back. + final c = _contact(receivedName: 'KQ4EZN-Repeater', customName: ''); + + expect(c.name, 'KQ4EZN-Repeater'); + }); + + test('T4 - a whitespace-only custom name counts as unset', () { + final c = _contact(receivedName: 'KQ4EZN-Repeater', customName: ' '); + + expect(c.name, 'KQ4EZN-Repeater'); + }); + + test( + 'T5 + copyWith(receivedName:) updates it and keeps the custom name', + () { + final c = _contact( + receivedName: 'old-advert-name', + customName: 'Chuck', + ).copyWith(receivedName: 'new-advert-name'); + + expect(c.receivedName, 'new-advert-name'); + expect(c.customName, 'Chuck'); + }, + ); + + test('T6 - copyWith(receivedName:) does not change the displayed name', () { + // This is the whole point of the epic: an advert updates what the node + // calls itself and never disturbs what the user calls it. + final c = _contact( + receivedName: 'old-advert-name', + customName: 'Chuck', + ).copyWith(receivedName: 'new-advert-name'); + + expect(c.name, 'Chuck'); + }); + + test('T6b + clearing the custom name reveals the newest received name', () { + final renamed = _contact( + receivedName: 'old-advert-name', + customName: 'Chuck', + ).copyWith(receivedName: 'new-advert-name', clearCustomName: true); + + expect(renamed.customName, isNull); + expect(renamed.name, 'new-advert-name'); + }); + + test('T28 - a custom name keeps CJK, emoji and ZWJ sequences intact', () { + // A custom name never crosses the wire, so #636's grapheme truncation + // must not be applied to it. + const rich = '测试 🧙‍♂️ Chuck'; + final c = _contact(receivedName: 'plain', customName: rich); + + expect(c.name, rich); + expect(c.customName, rich); + }); + }); +} diff --git a/test/models/contact_share_uri_test.dart b/test/models/contact_share_uri_test.dart index 8ed02f8c..c4e88f8d 100644 --- a/test/models/contact_share_uri_test.dart +++ b/test/models/contact_share_uri_test.dart @@ -165,7 +165,7 @@ void main() { group('Contact share URI emit (#626)', () { Contact stub(String name, int type) => Contact( publicKey: hex2Uint8List(_key), - name: name, + receivedName: name, type: type, pathLength: -1, path: Uint8List(0), @@ -232,7 +232,7 @@ void main() { group('Compact channel contact share (#611)', () { Contact stub(String name, int type) => Contact( publicKey: hex2Uint8List(_key), - name: name, + receivedName: name, type: type, pathLength: -1, path: Uint8List(0), diff --git a/test/models/path_selection_test.dart b/test/models/path_selection_test.dart index b3ffbbc3..b4de0d48 100644 --- a/test/models/path_selection_test.dart +++ b/test/models/path_selection_test.dart @@ -14,7 +14,7 @@ Contact _contact({ }) { return Contact( publicKey: Uint8List(32), - name: 'R', + receivedName: 'R', type: advTypeRepeater, pathLength: pathLength, pathHashWidth: pathHashWidth, diff --git a/test/screens/discover_regions_screen_test.dart b/test/screens/discover_regions_screen_test.dart index 35b6385a..e6031ef8 100644 --- a/test/screens/discover_regions_screen_test.dart +++ b/test/screens/discover_regions_screen_test.dart @@ -13,7 +13,7 @@ import 'package:meshcore_open/services/region_discovery_service.dart'; Contact _repeater() => Contact( publicKey: Uint8List(32), - name: 'rpt-01', + receivedName: 'rpt-01', type: advTypeRepeater, pathLength: 0, path: Uint8List(0), diff --git a/test/services/path_history_service_test.dart b/test/services/path_history_service_test.dart index cce2c6a2..4949b4d1 100644 --- a/test/services/path_history_service_test.dart +++ b/test/services/path_history_service_test.dart @@ -51,7 +51,7 @@ Contact _makeContact({ } return Contact( publicKey: bytes, - name: 'Test', + receivedName: 'Test', type: 1, pathLength: pathLength, path: Uint8List.fromList(path), diff --git a/test/services/repeater_command_service_test.dart b/test/services/repeater_command_service_test.dart index c7913e3b..19e6f939 100644 --- a/test/services/repeater_command_service_test.dart +++ b/test/services/repeater_command_service_test.dart @@ -19,7 +19,7 @@ import 'package:shared_preferences/shared_preferences.dart'; Contact _repeater() => Contact( publicKey: Uint8List.fromList(List.generate(32, (i) => i)), - name: 'Test Repeater', + receivedName: 'Test Repeater', type: 2, pathLength: 0, path: Uint8List(0), diff --git a/test/services/retry_and_protocol_test.dart b/test/services/retry_and_protocol_test.dart index 0860f2d6..d5f86c86 100644 --- a/test/services/retry_and_protocol_test.dart +++ b/test/services/retry_and_protocol_test.dart @@ -62,7 +62,7 @@ Contact _makeContact({ }) { return Contact( publicKey: publicKey, - name: 'Test', + receivedName: 'Test', type: 1, pathLength: pathLength, path: Uint8List.fromList(path), diff --git a/test/services/stock_config_export_service_test.dart b/test/services/stock_config_export_service_test.dart index 3ed8db8f..83435d9e 100644 --- a/test/services/stock_config_export_service_test.dart +++ b/test/services/stock_config_export_service_test.dart @@ -27,7 +27,7 @@ Contact makeContact({ }) { return Contact( publicKey: Uint8List(32), - name: name, + receivedName: name, type: type, flags: flags, pathLength: pathLength, diff --git a/test/storage/contact_naming_storage_test.dart b/test/storage/contact_naming_storage_test.dart new file mode 100644 index 00000000..c697bd23 --- /dev/null +++ b/test/storage/contact_naming_storage_test.dart @@ -0,0 +1,172 @@ +// Custom Name override for contacts (#750), storage half. +// +// Tests T7, T8, T9, T31 and T32 from the plan of record, +// docs/initiatives/standalone/750-contact-naming/PLAN.md. +// +// T32 is the data-loss guard that the plan correction on #750 added. Persisting +// `contact.name` instead of `contact.receivedName` would write a user's private +// label into the `name` key, and the next load would read it back as what the +// node calls itself. The real name would be gone permanently, with no advert +// able to restore it because the contact would already appear to have it. + +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/storage/contact_settings_store.dart'; +import 'package:meshcore_open/storage/contact_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'; + +const _radioKey = 'd549bbfbd003e580'; +const _contactKey = '00112233445566778899aabbccddeeff'; + +Contact _contact({required String receivedName, String? customName}) => Contact( + publicKey: Uint8List.fromList(List.filled(32, 0x22)), + receivedName: receivedName, + customName: customName, + type: 1, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.utc(2026, 7, 1), +); + +void main() { + late OffbandDatabase db; + late BlobStore blobs; + late ContactStore store; + late ContactSettingsStore settings; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + store = ContactStore()..setPublicKeyHex = _radioKey; + settings = ContactSettingsStore()..setPublicKeyHex = _radioKey; + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + group('contact_store and the received name (#750)', () { + test('T7 + a stored contact round-trips its received name', () async { + await store.saveContacts([_contact(receivedName: 'KQ4EZN-Repeater')]); + final loaded = await store.loadContacts(); + + expect(loaded.single.receivedName, 'KQ4EZN-Repeater'); + expect(loaded.single.name, 'KQ4EZN-Repeater'); + }); + + test('T8 - loading never invents a custom name', () async { + // If the migration populated customName from the stored name, every + // existing contact would silently become "renamed" and adverts would + // stop updating any of them. That is the worst failure in this epic and + // a positive-only suite would never see it. + await store.saveContacts([_contact(receivedName: 'KQ4EZN-Repeater')]); + final loaded = await store.loadContacts(); + + expect(loaded.single.customName, isNull); + }); + + test( + 'T32 - saving a renamed contact keeps the received name on disk', + () async { + // The data-loss guard. `contact.name` would be 'Chuck' here. + await store.saveContacts([ + _contact(receivedName: 'KQ4EZN-Repeater', customName: 'Chuck'), + ]); + final loaded = await store.loadContacts(); + + expect( + loaded.single.receivedName, + 'KQ4EZN-Repeater', + reason: 'the custom name must not be persisted as the received name', + ); + expect( + loaded.single.customName, + isNull, + reason: + 'contact_store does not own the custom name; a radio sync ' + 'rebuilds this record and would wipe it', + ); + }, + ); + + test( + 'T31 - a legacy row with no name loads as Unknown, not a crash', + () async { + // `receivedName` is non-nullable, and the pre-#750 reader had + // `json['name'] as String? ?? 'Unknown'`. Dropping that fallback during + // the rename would crash the load for anyone holding such a row. + await BlobStore.instance.write( + store.keyFor, + '[{"publicKey":"${base64OfKey()}","type":1,"pathLength":-1,"lastSeen":0}]', + ); + + final loaded = await store.loadContacts(); + + expect(loaded.single.receivedName, 'Unknown'); + expect(loaded.single.name, 'Unknown'); + }, + ); + }); + + group('contact_settings_store owns the custom name (#750)', () { + test('T9 + a custom name round-trips', () async { + await settings.saveCustomName(_contactKey, 'Chuck'); + + expect(await settings.loadCustomName(_contactKey), 'Chuck'); + }); + + test( + 'T9b - an unknown contact returns null, not an empty string', + () async { + expect(await settings.loadCustomName('ffffffffffffffff'), isNull); + }, + ); + + test('T9c + clearing with null removes it', () async { + await settings.saveCustomName(_contactKey, 'Chuck'); + await settings.saveCustomName(_contactKey, null); + + expect(await settings.loadCustomName(_contactKey), isNull); + }); + + test( + 'T9d - saving an empty name stores nothing, not an empty string', + () async { + // The store is the second enforcement point for "empty counts as unset", + // so a UI that passes '' cannot leave a contact with a blank name. + await settings.saveCustomName(_contactKey, 'Chuck'); + await settings.saveCustomName(_contactKey, ''); + + expect(await settings.loadCustomName(_contactKey), isNull); + }, + ); + + test('T9e - saving a whitespace-only name stores nothing', () async { + await settings.saveCustomName(_contactKey, 'Chuck'); + await settings.saveCustomName(_contactKey, ' '); + + expect(await settings.loadCustomName(_contactKey), isNull); + }); + + test('T9f + a custom name with emoji and CJK survives storage', () async { + const rich = '测试 🧙‍♂️ Chuck'; + await settings.saveCustomName(_contactKey, rich); + + expect(await settings.loadCustomName(_contactKey), rich); + }); + }); +} + +/// Base64 of the 32-byte key used by [_contact], for the legacy-row fixture. +String base64OfKey() => 'IiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiI='; diff --git a/test/storage/contact_store_test.dart b/test/storage/contact_store_test.dart index e892177e..f9b09ed0 100644 --- a/test/storage/contact_store_test.dart +++ b/test/storage/contact_store_test.dart @@ -14,7 +14,7 @@ import 'package:shared_preferences/shared_preferences.dart'; /// wrote whatever was in memory over the stored contacts. Contact _contact(int keyByte, String name) => Contact( publicKey: Uint8List.fromList(List.filled(32, keyByte)), - name: name, + receivedName: name, type: 1, pathLength: -1, path: Uint8List(0), diff --git a/test/widgets/contact_verification_badge_test.dart b/test/widgets/contact_verification_badge_test.dart index 3eea4ace..27501733 100644 --- a/test/widgets/contact_verification_badge_test.dart +++ b/test/widgets/contact_verification_badge_test.dart @@ -22,7 +22,7 @@ const _key = '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'; Contact _contact({required DateTime lastSeen}) => Contact( publicKey: hex2Uint8List(_key), - name: 'Bob', + receivedName: 'Bob', type: advTypeChat, pathLength: -1, path: Uint8List(0),