feat(#1170): log every contact removal by name, favorite and path

Contacts, favorites included, disappear (#1167), and every removal was
logged as a count, so nothing showed which contact went or why. This is
the first step of #1167: name each one, then fix the path the log names.
Which contacts are removed does not change.

- Each path that drops a contact, or asks the radio to delete one, logs
  a line per contact: name, short key, favorite flag, the path, and the
  connected radio. The paths are a complete sync that did not include
  it, a "not found" answer in recovery, the owner choosing the radio's
  list, a user delete, and a synced contact holding the radio's own key.
- The radio's push for a contact it overwrote to make room (0x8F) and
  for a full table (0x90) are logged. 0x90 is logged once per
  connection, since the radio sends it for every node it cannot add
  (Gemini).
- The radio's auto-add settings, read at every connect, are logged,
  overwrite oldest included, so each removal reads against them.

Rebased onto #1028 (PR #1185), which already handles 0x8F and 0x90: it
drops the overwritten contact and tracks the full table. The logging goes
into those handlers instead of a second pair of cases, and the 0x8F test
now expects the contact removed here, as #1028 does. The owner tested
this same combination on hardware in the combined build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/1197/head
diffwireauto 3 days ago committed by Strycher
parent b3a194a356
commit f697bc70a1

@ -418,6 +418,7 @@ class MeshCoreConnector extends ChangeNotifier {
final List<ScanResult> _scanResults = [];
final List<ScanResult> _systemScanResults = [];
final List<Contact> _contacts = [];
bool _contactsFullLogged = false;
final List<Contact> _discoveredContacts = [];
final List<Channel> _channels = [];
final Map<String, List<Message>> _conversations = {};
@ -5237,6 +5238,7 @@ class MeshCoreConnector extends ChangeNotifier {
_deviceDisplayName = null;
_deviceId = null;
_contacts.clear();
_contactsFullLogged = false;
_customNames.clear(); // per radio: none may outlive the link (#750, T37b)
_discoveredContacts.clear();
_conversations.clear();
@ -5859,11 +5861,14 @@ class MeshCoreConnector extends ChangeNotifier {
_recoveryDelivered.addAll(_contactSyncDeliveredKeys);
if (declared != null) _recoveryDeclared = declared;
if (isContactSyncComplete(declared: declared, received: received)) {
final before = _contacts.length;
final dropped = _contacts
.where((c) => !_contactSyncDeliveredKeys.contains(c.publicKeyHex))
.toList();
_contacts.removeWhere(
(c) => !_contactSyncDeliveredKeys.contains(c.publicKeyHex),
);
final removed = before - _contacts.length;
_logContactRemovals('complete sync did not include it', dropped);
final removed = dropped.length;
if (removed > 0) {
_appDebugLogService?.info(
'Contact sync complete ($received of $declared): removed $removed '
@ -5997,7 +6002,11 @@ class MeshCoreConnector extends ChangeNotifier {
final accounted = _recoveryDelivered.length;
if (declared != null && accounted >= declared) {
final gone = Set<String>.of(_recoveryGone);
final dropped = _contacts
.where((c) => gone.contains(c.publicKeyHex))
.toList();
_contacts.removeWhere((c) => gone.contains(c.publicKeyHex));
_logContactRemovals('radio answered not found', dropped);
_appDebugLogService?.info(
'Contact recovery complete ($accounted of $declared): removed '
'${gone.length} contact(s) the radio no longer holds',
@ -6041,8 +6050,12 @@ class MeshCoreConnector extends ChangeNotifier {
/// The owner chose the radio's list after a short sync: drop what no sync on
/// this connection delivered (confirmed gone, or never sent by the radio).
Future<void> resolveContactSyncUseRadio() async {
final removed = contactSyncUndeliveredCount;
final dropped = _contacts
.where((c) => !_recoveryDelivered.contains(c.publicKeyHex))
.toList();
final removed = dropped.length;
_contacts.removeWhere((c) => !_recoveryDelivered.contains(c.publicKeyHex));
_logContactRemovals('owner chose the radio list', dropped);
_contactSyncDecisionPending = false;
_contactSyncShortfall = null;
_appDebugLogService?.warn(
@ -6053,6 +6066,26 @@ class MeshCoreConnector extends ChangeNotifier {
await _persistContacts();
}
/// One line per contact the app drops or asks the radio to delete, so a
/// contact that disappears can be traced to what took it (#1170).
void _logContactRemovals(String path, Iterable<Contact> removed) {
for (final c in removed) {
_appDebugLogService?.warn(
'Contact removed ($path): ${_describeContact(c.publicKeyHex, c)}',
tag: 'ContactSync',
);
}
}
String _describeContact(String keyHex, Contact? contact) =>
'"${contact?.name ?? 'unknown'}" key ${keyHex.substring(0, 8)}'
'${contact?.isFavorite == true ? ', favorite' : ''}, radio $_radioForLog';
String get _radioForLog {
final prefix = AppSettingsService.radioScopePrefix(selfPublicKeyHex);
return prefix.isEmpty ? 'unknown' : prefix;
}
void dismissContactSyncShortfall() {
if (_contactSyncDecisionPending) return;
_contactSyncShortfall = null;
@ -6748,9 +6781,13 @@ class MeshCoreConnector extends ChangeNotifier {
notifyListeners();
}
Future<void> removeContact(Contact contact) async {
Future<void> removeContact(
Contact contact, {
String reason = 'user delete',
}) async {
if (!isConnected) return;
_logContactRemovals(reason, [contact]);
_handleDiscovery(
contact,
contact.rawPacket ?? Uint8List(0),
@ -6786,7 +6823,8 @@ class MeshCoreConnector extends ChangeNotifier {
final index = _contacts.indexWhere((c) => c.publicKeyHex == keyHex);
if (index < 0) {
_appDebugLogService?.info(
'Radio removed a contact to make room that this app did not hold',
'Radio overwrote contact ${_describeContact(keyHex, null)} to make '
'room; this app did not hold it',
tag: 'ContactSync',
);
return;
@ -6800,7 +6838,8 @@ class MeshCoreConnector extends ChangeNotifier {
);
unawaited(_persistContacts());
_appDebugLogService?.warn(
'Radio removed contact ${contact.name} to make room',
'Radio overwrote contact ${_describeContact(keyHex, contact)} to make '
'room; removed here too, messages kept',
tag: 'ContactSync',
);
_contactTableNotice = ContactTableNotice.removed(contact.name);
@ -9274,10 +9313,16 @@ class MeshCoreConnector extends ChangeNotifier {
_handleContactDeletedByRadio(frame);
break;
case pushCodeContactsFull:
_appDebugLogService?.warn(
'Radio reports its contact list is full',
tag: 'ContactSync',
);
// The radio sends this for every node it cannot add, so a busy mesh
// would flood the log: once per connection is enough. (Gemini)
if (!_contactsFullLogged) {
_contactsFullLogged = true;
_appDebugLogService?.warn(
'Radio contact table is full: a new contact was not saved (radio '
'$_radioForLog). Repeats on this connection are not logged',
tag: 'ContactSync',
);
}
_radioContactsFull = true;
if (_contactTableNotice == null) {
_contactTableNotice = const ContactTableNotice.full();
@ -10245,7 +10290,7 @@ class MeshCoreConnector extends ChangeNotifier {
tag: 'Connector',
);
notifyListeners();
removeContact(contactTmp);
removeContact(contactTmp, reason: "contact has this radio's own key");
return;
}
final contact = getFromDiscovered(contactTmp);
@ -13002,6 +13047,14 @@ class MeshCoreConnector extends ChangeNotifier {
if (frame.length > 2) {
_autoAddMaxHops = reader.readByte();
}
String onOff(bool on) => on ? 'on' : 'off';
_appDebugLogService?.info(
'Radio $_radioForLog auto-add: overwrite oldest ${onOff(_overwriteOldest)}, chat '
'${onOff(_autoAddUsers)}, repeater ${onOff(_autoAddRepeaters)}, room '
'${onOff(_autoAddRoomServers)}, sensor ${onOff(_autoAddSensors)}, '
'max hops $_autoAddMaxHops',
tag: 'ContactSync',
);
} catch (e) {
appLogger.error('Failed to parse auto-add config: $e', tag: 'Connector');
}

@ -0,0 +1,282 @@
// #1170 (part of #1167): every contact the app drops, or asks the radio to
// delete, is logged by name, favorite flag, path and radio, so a contact that
// disappears can be traced to what took it. Logging only: which contacts are
// removed does not change.
import 'dart:convert';
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/services/app_debug_log_service.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:meshcore_open/utils/app_logger.dart';
import 'package:shared_preferences/shared_preferences.dart';
final _radioKey = Uint8List.fromList(List<int>.filled(32, 0xA1));
const _radio = 'a1a1a1a1a1';
Uint8List _u32(int v) =>
Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little);
Uint8List _contactFrame(int keyByte, String name, {List<int>? key}) {
final b = BytesBuilder()
..addByte(respCodeContact)
..add(key ?? List<int>.filled(32, keyByte))
..addByte(advTypeChat)
..addByte(0)
..addByte(0xFF)
..add(List<int>.filled(64, 0))
..add(Uint8List(32)..setRange(0, name.length, utf8.encode(name)))
..add(_u32(1790000000))
..add(_u32(0))
..add(_u32(0))
..add(_u32(1790000000));
return b.toBytes();
}
Uint8List _start(int declared) =>
Uint8List.fromList([respCodeContactsStart, ..._u32(declared)]);
Uint8List get _end => Uint8List.fromList([respCodeEndOfContacts, ..._u32(0)]);
Contact _saved(int keyByte, String name, {bool favorite = false}) => Contact(
publicKey: Uint8List.fromList(List<int>.filled(32, keyByte)),
receivedName: name,
type: advTypeChat,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.utc(2026, 7, 1),
flags: favorite ? contactFlagFavorite : 0,
);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late OffbandDatabase db;
late MeshCoreConnector connector;
late AppDebugLogService log;
late List<Uint8List> sent;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
connector = MeshCoreConnector();
connector.contactRecoverySettle = Duration.zero;
connector.contactKeyCheckGap = Duration.zero;
connector.contactKeyCheckTimeout = const Duration(milliseconds: 20);
sent = [];
connector.sendFrameOverrideForTest = sent.add;
connector.setConnectedForTest();
connector.setSelfPublicKeyForTest(_radioKey);
log = AppDebugLogService()..setEnabled(true);
appLogger.initialize(log, enabled: true);
connector.setAppDebugLogServiceForTest(log);
});
tearDown(() async {
BlobStore.clearTestOverride();
await db.close();
});
List<String> lines(String fragment) => log.entries
.map((e) => e.message)
.where((m) => m.contains(fragment))
.toList();
Future<void> settle() =>
Future<void>.delayed(const Duration(milliseconds: 5));
Future<void> answerStream(int declared, List<Uint8List> streamed) async {
connector.handleFrameForTest(_start(declared));
for (final f in streamed) {
connector.handleFrameForTest(f);
}
connector.handleFrameForTest(_end);
await settle();
}
void seed() {
connector.contactsForTest
..add(_saved(0x11, 'Alpha'))
..add(_saved(0x22, 'Bravo', favorite: true))
..add(_saved(0x33, 'Charlie'));
}
test('a complete sync names each contact it drops', () async {
seed();
await connector.getContacts();
await answerStream(1, [_contactFrame(0x11, 'Alpha')]);
final removed = lines('Contact removed');
expect(removed, hasLength(2));
final bravo = removed.singleWhere((m) => m.contains('"Bravo"'));
expect(bravo, contains('favorite'));
expect(bravo, contains('complete sync did not include it'));
expect(bravo, contains('key 22222222'));
expect(bravo, contains('radio $_radio'));
final charlie = removed.singleWhere((m) => m.contains('"Charlie"'));
expect(charlie, isNot(contains('favorite')));
});
test('a contact the radio answers "not found" for is named', () async {
// Two short syncs add up to the declared 3 without Bravo, so the app asks
// the radio about Bravo by key.
seed();
connector.contactsForTest.add(_saved(0x44, 'Delta'));
await connector.getContacts();
await answerStream(3, [
_contactFrame(0x11, 'Alpha'),
_contactFrame(0x33, 'Charlie'),
]);
await answerStream(3, [
_contactFrame(0x11, 'Alpha'),
_contactFrame(0x44, 'Delta'),
]);
connector.handleFrameForTest(
Uint8List.fromList([respCodeErr, errCodeNotFound]),
);
await settle();
final removed = lines('Contact removed');
expect(removed, hasLength(1));
expect(removed.single, contains('"Bravo"'));
expect(removed.single, contains('favorite'));
expect(removed.single, contains('radio answered not found'));
});
test('choosing the radio list names each contact it drops', () async {
seed();
final alpha = [_contactFrame(0x11, 'Alpha')];
await connector.getContacts();
await answerStream(350, alpha);
await answerStream(350, alpha);
await answerStream(350, alpha);
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(lines('Contact removed'), isEmpty, reason: 'nothing removed yet');
await connector.resolveContactSyncUseRadio();
final removed = lines('Contact removed');
expect(removed, hasLength(2));
expect(
removed.singleWhere((m) => m.contains('"Bravo"')),
allOf(contains('favorite'), contains('owner chose the radio list')),
);
});
test('a user delete is named before the radio is told', () async {
seed();
final bravo = connector.contactsForTest[1];
await connector.removeContact(bravo);
final removed = lines('Contact removed');
expect(removed, hasLength(1));
expect(removed.single, contains('"Bravo"'));
expect(removed.single, contains('favorite'));
expect(removed.single, contains('user delete'));
expect(sent.where((f) => f[0] == cmdRemoveContact), hasLength(1));
});
test('a contact holding the radio\'s own key is named', () async {
connector.handleFrameForTest(
_contactFrame(0, 'Myself', key: _radioKey.toList()),
);
await settle();
final removed = lines('Contact removed');
expect(removed, hasLength(1));
expect(removed.single, contains('"Myself"'));
expect(removed.single, contains("this radio's own key"));
expect(removed.single, contains('radio $_radio'));
});
// #1028: the radio is the truth, so the app drops the contact it overwrote.
test('the radio overwriting a contact is logged, and removes it here', () {
seed();
connector.handleFrameForTest([
pushCodeContactDeleted,
...List.filled(32, 0x33),
]);
final line = lines('Radio overwrote').single;
expect(line, contains('"Charlie"'));
expect(line, contains('key 33333333'));
expect(line, contains('radio $_radio'));
expect(
connector.contactsForTest.map((c) => c.name),
isNot(contains('Charlie')),
);
});
test('the radio overwriting a favorite says so', () {
seed();
connector.handleFrameForTest([
pushCodeContactDeleted,
...List.filled(32, 0x22),
]);
expect(lines('Radio overwrote').single, contains('favorite'));
});
test('the radio overwriting a contact the app never had is logged', () {
connector.handleFrameForTest([
pushCodeContactDeleted,
...List.filled(32, 0x77),
]);
expect(lines('Radio overwrote').single, contains('key 77777777'));
});
test('a full contact table on the radio is logged', () {
connector.handleFrameForTest([pushCodeContactsFull]);
connector.handleFrameForTest([pushCodeContactsFull]);
connector.handleFrameForTest([pushCodeContactsFull]);
expect(
lines('contact table is full').single,
contains('radio $_radio'),
reason: 'the radio repeats this per node it cannot add: logged once',
);
});
test('a radio whose key is not known yet is named "unknown"', () async {
final unknown = MeshCoreConnector()
..sendFrameOverrideForTest = sent.add
..setConnectedForTest()
..setAppDebugLogServiceForTest(log)
..contactsForTest.add(_saved(0x11, 'Alpha'));
await unknown.removeContact(unknown.contactsForTest.single);
expect(lines('Contact removed').single, contains('radio unknown'));
});
test('the overwrite setting is logged when the radio reports it', () {
connector.handleFrameForTest([
respCodeAutoAddConfig,
autoAddChatFlag | autoAddOverwriteOldestFlag,
3,
]);
connector.handleFrameForTest([respCodeAutoAddConfig, autoAddRepeaterFlag]);
final settings = lines('auto-add');
expect(settings, hasLength(2));
expect(settings[0], contains('Radio $_radio'));
expect(settings[0], contains('overwrite oldest on'));
expect(settings[0], contains('chat on'));
expect(settings[1], contains('overwrite oldest off'));
expect(settings[1], contains('repeater on'));
});
}
Loading…
Cancel
Save

Powered by TurnKey Linux.