feat(#750): reattach the custom name wherever a Contact is rebuilt

Task 750.3 of the contact-naming plan. The custom name lives in contact_settings_store keyed by pubkey, not in contact_store, so the live Contact objects have to be reattached to it. Two paths drop it otherwise, and both fail silently.

Cache hydrate rebuilds every Contact from contact_store, which does not hold the custom name on purpose, so a restart would lose every rename the user made. Radio contact-sync replaces an existing Contact with one built from the device frame, where no custom name exists.

Adds a _customNames map as the in-memory mirror, _withCustomName to reattach, and _loadCustomNames to batch the load. Batched for the reason already documented on the cyr2lat loader: a notify per contact rebuilds the tree twice per contact and each rebuild walks the contact list.

Applied at five sites: cache hydrate and the four contact-sync rebuilds. Paths that copyWith from an EXISTING contact need nothing, because copyWith preserves customName unless clearCustomName is passed, which is why the advert handler from 750.1 already behaves.

setContactCustomName is the write path. Null, empty and whitespace all clear, matching Contact.name and the store, so a user who deletes the field's text cannot end up with a blank name and no way back.

Eleven tests. T35 was falsified before being trusted: dropping the hydrate mapping made it fail alone. T16 to T22 guard behaviour 750.1 already delivered and passed on arrival, so they are regression guards rather than watched failures, and the file says so.

Gates: analyze --fatal-infos --fatal-warnings clean, dart format 0-changed, 1324 tests passed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
pull/1001/head
diffwireauto 1 month ago committed by Strycher
parent 1a3ab19a12
commit d9c356a4a4

@ -586,6 +586,17 @@ class MeshCoreConnector extends ChangeNotifier {
final ChannelRegionScopeStore _channelRegionScopeStore =
ChannelRegionScopeStore();
final ContactSettingsStore _contactSettingsStore = ContactSettingsStore();
/// Custom names by pubkey hex, the in-memory mirror of what
/// `contact_settings_store` holds. (#750)
///
/// Needed because `contact_store` deliberately does not persist the custom
/// name: that record is rebuilt from radio contact-sync data, so a save
/// after a sync would wipe it. The cost of keeping it out of there is that
/// the live `Contact` objects have to be reattached to it, which is what
/// [_withCustomName] does at every path that rebuilds one.
final Map<String, String> _customNames = {};
final ContactStore _contactStore = ContactStore();
final ContactDiscoveryStore _discoveryContactStore = ContactDiscoveryStore();
final ChannelStore _channelStore = ChannelStore();
@ -2208,6 +2219,64 @@ class MeshCoreConnector extends ChangeNotifier {
notifyListeners();
}
/// Reattaches the stored custom name to [contact], if the user set one.
///
/// Call this anywhere a `Contact` is built from the radio or from
/// `contact_store`, because neither source carries the custom name. Paths
/// that use `copyWith` on an EXISTING contact do not need it: `copyWith`
/// preserves `customName` unless `clearCustomName` is passed. (#750)
/// Loads the stored custom names for [keys] into [_customNames] in one pass.
///
/// Batched rather than per-contact for the reason documented on
/// `_ensureContactCyr2LatSettingLoaded`: a notify per contact rebuilds the
/// tree twice per contact, and each rebuild walks the contact list.
Future<void> _loadCustomNames(Iterable<String> keys) async {
final loaded = await Future.wait([
for (final key in keys)
_contactSettingsStore
.loadCustomName(key)
.then((name) => MapEntry(key, name)),
]);
for (final entry in loaded) {
final name = entry.value;
if (name != null && name.trim().isNotEmpty) {
_customNames[entry.key] = name;
}
}
}
Contact _withCustomName(Contact contact) {
final custom = _customNames[contact.publicKeyHex];
if (custom == null) return contact;
return contact.copyWith(customName: custom);
}
/// The user's label for a contact, or null. Read by the contacts UI.
String? customNameFor(String contactKeyHex) => _customNames[contactKeyHex];
/// Sets or clears the user's label for a contact.
///
/// Null, empty and whitespace-only all clear it, matching `Contact.name` and
/// the store, so a user who deletes the field's text cannot end up with a
/// blank name and no way back. (T34b, T34c)
Future<void> setContactCustomName(String contactKeyHex, String? name) async {
final cleaned = (name == null || name.trim().isEmpty) ? null : name;
if (cleaned == null) {
_customNames.remove(contactKeyHex);
} else {
_customNames[contactKeyHex] = cleaned;
}
await _contactSettingsStore.saveCustomName(contactKeyHex, cleaned);
final index = _contacts.indexWhere((c) => c.publicKeyHex == contactKeyHex);
if (index >= 0) {
_contacts[index] = cleaned == null
? _contacts[index].copyWith(clearCustomName: true)
: _contacts[index].copyWith(customName: cleaned);
}
notifyListeners();
}
Future<void> setContactCyr2LatEnabled(
String contactKeyHex,
bool enabled,
@ -2353,9 +2422,14 @@ class MeshCoreConnector extends ChangeNotifier {
_knownContactKeys
..clear()
..addAll(cached.map((c) => c.publicKeyHex));
// Custom names first, so the contacts below are hydrated with them in one
// pass rather than rebuilt a second time. Without this a restart silently
// loses every rename the user made, because contact_store does not hold
// them on purpose. (#750, T35)
await _loadCustomNames(cached.map((c) => c.publicKeyHex));
_contacts
..clear()
..addAll(cached);
..addAll(cached.map(_withCustomName));
// Load every contact's settings without notifying per contact, then
// notify once. Per-contact notification rebuilt the whole tree 2x per
// contact (600 rebuilds for 300 contacts), and each rebuild walks the
@ -3860,6 +3934,20 @@ class MeshCoreConnector extends ChangeNotifier {
void resetConnectionHandshakeStateForTest() =>
_resetConnectionHandshakeState();
/// Scopes the contact stores to [radioKeyHex] and hydrates the cache, which
/// normally happens as part of the connect handshake. (#750)
@visibleForTesting
Future<void> loadContactCacheForTest(String radioKeyHex) async {
_contactStore.setPublicKeyHex = radioKeyHex;
_contactSettingsStore.setPublicKeyHex = radioKeyHex;
await loadContactCache();
}
/// Scopes the contact settings store without a connect handshake. (#750)
@visibleForTesting
void setContactSettingsKeyForTest(String radioKeyHex) =>
_contactSettingsStore.setPublicKeyHex = radioKeyHex;
/// Feeds a device frame through the normal dispatch, so parse paths can be
/// exercised without a radio. (#578)
@visibleForTesting
@ -8064,12 +8152,16 @@ class MeshCoreConnector extends ChangeNotifier {
// Preserve user-selected path settings and previously known GPS when
// refreshed frames omit coordinates (lat/lon encoded as 0,0).
_contacts[existingIndex] = contact.copyWith(
lastMessageAt: mergedLastMessageAt,
pathOverride: existing.pathOverride, // Preserve user's path choice
pathOverrideBytes: existing.pathOverrideBytes,
latitude: contact.latitude ?? existing.latitude,
longitude: contact.longitude ?? existing.longitude,
// `contact` is built from the device frame, which carries no custom
// name, so copyWith from it drops the user's label. Reattach it. (#750)
_contacts[existingIndex] = _withCustomName(
contact.copyWith(
lastMessageAt: mergedLastMessageAt,
pathOverride: existing.pathOverride, // Preserve user's path choice
pathOverrideBytes: existing.pathOverrideBytes,
latitude: contact.latitude ?? existing.latitude,
longitude: contact.longitude ?? existing.longitude,
),
);
appLogger.info(
@ -8079,7 +8171,7 @@ class MeshCoreConnector extends ChangeNotifier {
} else if (isContact) {
// The contact sync stream is radio truth; it is the only thing that
// populates the persisted list.
_contacts.add(contact);
_contacts.add(_withCustomName(contact));
appLogger.info(
'Added new contact ${contact.name}: pathLen=${_pathDiag(contact.path, contact.pathLength, contact.pathHashWidth)}',
tag: 'Connector',
@ -8177,10 +8269,13 @@ class MeshCoreConnector extends ChangeNotifier {
);
// CRITICAL: Preserve user's path override when contact is refreshed from device
_contacts[existingIndex] = contact.copyWith(
lastMessageAt: mergedLastMessageAt,
pathOverride: existing.pathOverride, // Preserve user's path choice
pathOverrideBytes: existing.pathOverrideBytes,
// Built from the device frame, so reattach the user's label. (#750)
_contacts[existingIndex] = _withCustomName(
contact.copyWith(
lastMessageAt: mergedLastMessageAt,
pathOverride: existing.pathOverride, // Preserve user's path choice
pathOverrideBytes: existing.pathOverrideBytes,
),
);
appLogger.info(
@ -8188,7 +8283,7 @@ class MeshCoreConnector extends ChangeNotifier {
tag: 'Connector',
);
} else {
_contacts.add(contact);
_contacts.add(_withCustomName(contact));
appLogger.info(
'Added new contact ${contact.name}: pathLen=${contact.pathLength}',
tag: 'Connector',

@ -0,0 +1,203 @@
// Custom Name override for contacts (#750), task 750.3: the live lifecycle.
//
// The custom name is stored in contact_settings_store keyed by pubkey, so it
// has to be reattached to the live Contact objects. Two paths drop it if the
// wiring is missing, and both are silent:
//
// 1. cache hydrate rebuilds every Contact from contact_store, which does not
// hold the custom name on purpose (a radio sync would wipe it there);
// 2. radio contact-sync replaces an existing Contact with one built from the
// device frame, where no custom name exists.
//
// Tests T15 to T22 from the plan, plus T34 and T35 for the two paths above.
//
// T15 to T22 guard behaviour that 750.1 already delivered, so they pass on
// arrival and are regression guards rather than watched failures. T34 and T35
// are the watched ones for this task.
import 'dart:typed_data';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/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 _received = 'KQ4EZN-Repeater';
const _custom = 'Chuck';
Uint8List _key(int b) => Uint8List.fromList(List<int>.filled(32, b));
Contact _contact({
int keyByte = 0x44,
String receivedName = _received,
String? customName,
}) => Contact(
publicKey: _key(keyByte),
receivedName: receivedName,
customName: customName,
type: advTypeChat,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.utc(2026, 7, 1),
);
void main() {
late OffbandDatabase db;
late MeshCoreConnector connector;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
connector = MeshCoreConnector();
connector.contactsForTest.clear();
});
tearDown(() async {
BlobStore.clearTestOverride();
await db.close();
});
group('a custom name survives the paths that rebuild a Contact (#750)', () {
test('T35 - cache hydrate restores the custom name', () async {
// contact_store deliberately does not persist customName, so without
// this wiring a restart silently loses every rename the user made.
final store = ContactStore()..setPublicKeyHex = _radioKey;
final settings = ContactSettingsStore()..setPublicKeyHex = _radioKey;
await store.saveContacts([_contact()]);
await settings.saveCustomName(_contact().publicKeyHex, _custom);
await connector.loadContactCacheForTest(_radioKey);
final loaded = connector.contactsForTest.single;
expect(loaded.customName, _custom);
expect(loaded.name, _custom);
expect(
loaded.receivedName,
_received,
reason: 'the received name must survive alongside it',
);
});
test('T35b + a contact with no custom name hydrates unchanged', () async {
final store = ContactStore()..setPublicKeyHex = _radioKey;
await store.saveContacts([_contact()]);
await connector.loadContactCacheForTest(_radioKey);
final loaded = connector.contactsForTest.single;
expect(loaded.customName, isNull);
expect(loaded.name, _received);
});
test(
'T34 + setting a custom name persists it and shows immediately',
() async {
final settings = ContactSettingsStore()..setPublicKeyHex = _radioKey;
connector.setContactSettingsKeyForTest(_radioKey);
connector.contactsForTest.add(_contact());
await connector.setContactCustomName(_contact().publicKeyHex, _custom);
expect(connector.contactsForTest.single.name, _custom);
expect(
await settings.loadCustomName(_contact().publicKeyHex),
_custom,
reason: 'it must reach storage, not just memory',
);
},
);
test(
'T34b + clearing a custom name reverts to the received name',
() async {
final settings = ContactSettingsStore()..setPublicKeyHex = _radioKey;
connector.setContactSettingsKeyForTest(_radioKey);
connector.contactsForTest.add(_contact(customName: _custom));
await connector.setContactCustomName(_contact().publicKeyHex, null);
expect(connector.contactsForTest.single.customName, isNull);
expect(connector.contactsForTest.single.name, _received);
expect(await settings.loadCustomName(_contact().publicKeyHex), isNull);
},
);
test(
'T34c - an empty custom name is treated as a clear, not stored',
() async {
final settings = ContactSettingsStore()..setPublicKeyHex = _radioKey;
connector.setContactSettingsKeyForTest(_radioKey);
connector.contactsForTest.add(_contact(customName: _custom));
await connector.setContactCustomName(_contact().publicKeyHex, ' ');
expect(connector.contactsForTest.single.name, _received);
expect(await settings.loadCustomName(_contact().publicKeyHex), isNull);
},
);
});
group('advert interaction, regression guards from 750.1 (#750)', () {
test('T16 - copyWith of a received name leaves the display name alone', () {
final c = _contact(
customName: _custom,
).copyWith(receivedName: 'renamed-on-its-radio');
expect(c.name, _custom);
expect(c.receivedName, 'renamed-on-its-radio');
});
test('T17 + clearing afterwards reveals the NEWEST received name', () {
final c = _contact(customName: _custom)
.copyWith(receivedName: 'renamed-on-its-radio')
.copyWith(clearCustomName: true);
expect(c.name, 'renamed-on-its-radio');
});
test('T19 - a received-name update never writes a custom name', () {
final c = _contact().copyWith(receivedName: 'new');
expect(c.customName, isNull);
});
test('T20 + a card-added contact is not advert-verified', () {
final carded = Contact(
publicKey: _key(0x55),
receivedName: 'Alice',
type: advTypeChat,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
);
expect(carded.isAdvertVerified, isFalse);
expect(carded.name, 'Alice');
});
test('T21 - a contact that has adverted IS verified', () {
expect(_contact().isAdvertVerified, isTrue);
});
test('T22 + a rename that never propagated still shows the user label', () {
// The owner's case: an operator renames their radio, the advert does not
// come, so the received name stays stale. The user's own label is what
// they see, and the stale received name is still there to show beside it.
final c = _contact(customName: _custom);
expect(c.name, _custom);
expect(c.receivedName, _received);
});
});
}
Loading…
Cancel
Save

Powered by TurnKey Linux.