fix(#1028): keep a contact only when the radio confirms it

The owner's log showed CMD_ADD_UPDATE_CONTACT drawing ERR 3 (table
full) while the app logged "Added new contact" and kept it. Every DM to
that contact then drew ERR 2 (not found) and went red only when the 8 s
timer ran out, with no reason.

- Both add paths (by key, and from Discovery, the map or a channel
  sender) wait for the radio's OK or ERR. The contact is kept only on
  OK. A refusal or no answer keeps nothing and tells the user which,
  with "full" said plainly. Owner decision 2026-11-23.
- The Discovery add now waits for its own reply, so its ERR can no
  longer be taken as the answer to the next command.
- A DM the radio refuses fails at once and keeps the radio's error
  code, which the failed bubble shows. Matched only when exactly one DM
  is waiting and no ERR-drawing stream is running.
- The radio removing a contact to make room (push 0x8F) removes it from
  the app and names it; its messages are kept. The radio reporting
  itself full (push 0x90), a refusal for a full table, or a complete
  sync at capacity raises a notice on the contacts screen.
- New strings are English-only; untranslated.json updated.

Tests: contact_add_confirm_test.dart uses only dev's API, and 5 of its
9 tests fail on dev (refused add kept twice, the Discovery ERR taking
the next command's reply, the refused DM pending, the removed contact
kept). contact_add_result_test.dart (17) and 3 new dialog tests cover
the results, the notice, the stored reason and the negative cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/1188/head
diffwireauto 3 days ago committed by Strycher
parent d770bdec49
commit 243070f586

@ -306,6 +306,31 @@ class ContactSyncShortfall {
/// What the radio said when asked for one contact by key. (#762)
enum ContactKeyCheckResult { onRadio, notFound, unresolved }
/// How a contact add ended. A contact is kept only on [added]. (#1028)
enum ContactAddOutcome { added, refused, noReply, notConnected }
class ContactAddResult {
const ContactAddResult(this.outcome, {this.errCode});
final ContactAddOutcome outcome;
/// The radio's error code when [outcome] is [ContactAddOutcome.refused].
final int? errCode;
bool get added => outcome == ContactAddOutcome.added;
bool get radioFull => errCode == errCodeTableFull;
}
/// Something the radio did to its contact table that the user has to know
/// about. Shown on the contacts screen until dismissed. (#1028)
class ContactTableNotice {
const ContactTableNotice.full() : removedName = null;
const ContactTableNotice.removed(String name) : removedName = name;
/// The contact the radio removed to make room, or null when the radio is
/// simply full.
final String? removedName;
}
/// Why a factory reset was not sent. (#1054)
enum FactoryResetRefusal { notConnected }
@ -649,6 +674,21 @@ class MeshCoreConnector extends ChangeNotifier {
@visibleForTesting
Duration contactKeyCheckTimeout = const Duration(seconds: 5);
@visibleForTesting
Duration contactAddReplyTimeout = const Duration(seconds: 5);
@visibleForTesting
set maxContactsForTest(int value) => _maxContacts = value;
ContactTableNotice? _contactTableNotice;
ContactTableNotice? get contactTableNotice => _contactTableNotice;
void dismissContactTableNotice() {
if (_contactTableNotice == null) return;
_contactTableNotice = null;
notifyListeners();
}
@visibleForTesting
DateTime Function() contactSyncClock = DateTime.now;
bool _isSyncingQueuedMessages = false;
@ -6686,6 +6726,37 @@ class MeshCoreConnector extends ChangeNotifier {
notifyListeners();
}
/// The radio removed a contact to make room for a new one
/// (`PUSH_CODE_CONTACT_DELETED`). The radio is the truth, so the app drops
/// it too and says which one. Its messages are kept: the user did not delete
/// anything, and re-adding the contact brings them back. (#1028)
void _handleContactDeletedByRadio(Uint8List frame) {
if (frame.length < 1 + pubKeySize) return;
final keyHex = pubKeyToHex(frame.sublist(1, 1 + pubKeySize));
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',
tag: 'ContactSync',
);
return;
}
final contact = _contacts.removeAt(index);
_knownContactKeys.remove(keyHex);
_handleDiscovery(
contact,
contact.rawPacket ?? Uint8List(0),
noNotify: true,
);
unawaited(_persistContacts());
_appDebugLogService?.warn(
'Radio removed contact ${contact.name} to make room',
tag: 'ContactSync',
);
_contactTableNotice = ContactTableNotice.removed(contact.name);
notifyListeners();
}
Future<void> updateKnownDiscovered() async {
if (!isConnected) return;
for (int i = 0; i < _discoveredContacts.length; i++) {
@ -6717,12 +6788,15 @@ class MeshCoreConnector extends ChangeNotifier {
/// unknown, so it needs no capability gate and works on stock firmware, not
/// just Offband builds.
///
/// Returns false when not connected. The radio answers with a generic OK, or
/// an error when its contact table is full.
Future<bool> addContactByKey(Contact stub) async {
if (!isConnected) return false;
/// The contact is kept only once the radio answers OK. An ERR (for example a
/// full contact table) or no answer keeps nothing. (#1028)
Future<ContactAddResult> addContactByKey(Contact stub) async {
if (!isConnected) {
return const ContactAddResult(ContactAddOutcome.notConnected);
}
await sendFrame(
final result = await _sendContactAdd(
stub.name,
buildUpdateContactPathFrame(
stub.publicKey,
// No path is known, so send an empty one and let the flood sentinel
@ -6742,21 +6816,76 @@ class MeshCoreConnector extends ChangeNotifier {
// to its own adverts. See buildUpdateContactPathFrame. (#620)
lastAdvert: DateTime.fromMillisecondsSinceEpoch(0),
),
expectsGenericAck: true,
);
if (!result.added) return result;
// Mirror the device write into local state, keeping lastSeen at the epoch
// so the contact continues to read as unverified until a real advert
// arrives and upgrades it. (#630)
_handleContactAdvert(stub);
notifyListeners();
return true;
return result;
}
Future<void> importDiscoveredContact(Contact contact) async {
if (!isConnected) return;
/// Sends one `CMD_ADD_UPDATE_CONTACT` and waits for the radio's OK or ERR on
/// the order-matched generic-ack queue, like [_writeChannelSlot]. (#1028)
Future<ContactAddResult> _sendContactAdd(String name, Uint8List frame) async {
final reply = Completer<int?>();
final pending = _PendingCommandAck(
commandCode: cmdAddUpdateContact,
reply: reply,
);
// Queued before the frame goes out, so a fast reply cannot arrive first.
_pendingGenericAckQueue.add(pending);
try {
await sendFrame(frame);
} catch (e) {
_pendingGenericAckQueue.remove(pending);
_appDebugLogService?.error(
'Contact add for $name was not sent: $e',
tag: 'ContactAdd',
);
return const ContactAddResult(ContactAddOutcome.noReply);
}
final int? errCode;
try {
errCode = await reply.future.timeout(contactAddReplyTimeout);
} on TimeoutException {
// Dropped so a late or lost reply cannot be matched to the next command.
_pendingGenericAckQueue.remove(pending);
_appDebugLogService?.warn(
'Radio did not answer the contact add for $name; not added',
tag: 'ContactAdd',
);
return const ContactAddResult(ContactAddOutcome.noReply);
}
if (errCode == null) {
_appDebugLogService?.info(
'Radio accepted contact $name',
tag: 'ContactAdd',
);
return const ContactAddResult(ContactAddOutcome.added);
}
_appDebugLogService?.warn(
'Radio refused contact $name (error $errCode); not added',
tag: 'ContactAdd',
);
if (errCode == errCodeTableFull) {
_contactTableNotice = const ContactTableNotice.full();
notifyListeners();
}
return ContactAddResult(ContactAddOutcome.refused, errCode: errCode);
}
await sendFrame(
/// Adds a contact heard on the mesh. Kept only once the radio answers OK,
/// like [addContactByKey]. (#1028)
Future<ContactAddResult> importDiscoveredContact(Contact contact) async {
if (!isConnected) {
return const ContactAddResult(ContactAddOutcome.notConnected);
}
final result = await _sendContactAdd(
contact.name,
buildUpdateContactPathFrame(
contact.publicKey,
contact.path,
@ -6770,6 +6899,7 @@ class MeshCoreConnector extends ChangeNotifier {
lastModified: contact.lastSeen,
),
);
if (!result.added) return result;
// Update the discovered contact to mark it as active (imported)
final discoveredIndex = _discoveredContacts.indexWhere(
@ -6794,6 +6924,7 @@ class MeshCoreConnector extends ChangeNotifier {
),
);
notifyListeners();
return result;
}
Future<void> clearContactPath(Contact contact) async {
@ -8987,6 +9118,17 @@ class MeshCoreConnector extends ChangeNotifier {
case pushCodeAdvert:
// Known contact was seen again - just a pub key, no action needed
break;
case pushCodeContactDeleted:
_handleContactDeletedByRadio(frame);
break;
case pushCodeContactsFull:
_appDebugLogService?.warn(
'Radio reports its contact list is full',
tag: 'ContactSync',
);
_contactTableNotice = const ContactTableNotice.full();
notifyListeners();
break;
case pushCodeNewAdvert:
debugPrint('Got New CONTACT');
// It's the same format as respCodeContact, so we can reuse the handler
@ -9004,6 +9146,13 @@ class MeshCoreConnector extends ChangeNotifier {
_hasLoadedContacts = true;
_contactSyncUsesSinceFilter = false;
if (wasFullSync) _finishFullContactSync();
if (wasFullSync && _contacts.length >= _maxContacts) {
_appDebugLogService?.warn(
'Radio contact list is full (${_contacts.length} of $_maxContacts)',
tag: 'ContactSync',
);
_contactTableNotice ??= const ContactTableNotice.full();
}
_runQueuedContactRequest();
unawaited(updateKnownDiscovered());
notifyListeners();
@ -9201,6 +9350,16 @@ class MeshCoreConnector extends ChangeNotifier {
}
if (_pendingGenericAckQueue.isEmpty) {
// A DM the radio refused (for example NOT_FOUND for a contact it does
// not hold) answers with this ERR instead of RESP_CODE_SENT. Fail it now
// with the reason rather than after the 8 s timer. Only claimed when no
// stream that also draws ERRs is running. (#1028)
if (!_contactRequestInFlight &&
!_isSyncingChannels &&
!_channelSyncInFlight &&
!caplogWasAwaitingStart) {
_retryService?.failAwaitingSendOnRadioError(errCode);
}
return;
}
@ -12156,6 +12315,7 @@ class MeshCoreConnector extends ChangeNotifier {
_pendingChannelSentQueue.clear();
_pendingGenericAckQueue.clear();
_reactionSendQueueSequence = 0;
_contactTableNotice = null;
_setState(MeshCoreConnectionState.disconnected);
_scheduleReconnect();
@ -12445,19 +12605,21 @@ class MeshCoreConnector extends ChangeNotifier {
return;
}
importDiscoveredContact(
Contact(
rawPacket: frame,
publicKey: publicKey,
receivedName: name,
type: type,
pathLength: pathBytes.isEmpty ? -1 : pathBytes.length,
path: Uint8List.fromList(
pathBytes.reversed.toList(),
), // Store path in reverse for easier use in outgoing messages
latitude: latitude,
longitude: longitude,
lastSeen: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000),
unawaited(
importDiscoveredContact(
Contact(
rawPacket: frame,
publicKey: publicKey,
receivedName: name,
type: type,
pathLength: pathBytes.isEmpty ? -1 : pathBytes.length,
path: Uint8List.fromList(
pathBytes.reversed.toList(),
), // Store path in reverse for easier use in outgoing messages
latitude: latitude,
longitude: longitude,
lastSeen: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000),
),
),
);
}

@ -503,6 +503,10 @@ const int errCodeUnsupportedCmd = 1;
/// not hold. (#762)
const int errCodeNotFound = 2;
/// `ERR_CODE_TABLE_FULL`: e.g. `CMD_ADD_UPDATE_CONTACT` when the radio's
/// contact table has no free slot. (#1028)
const int errCodeTableFull = 3;
/// `ERR_CODE_BAD_STATE`: e.g. `CMD_SET_CHANNEL` putting a different channel
/// over an occupied slot, which firmware with OffbandMesh/meshcore-firmware#1864
/// refuses. (#1026)
@ -957,6 +961,10 @@ const int pushCodeTraceData = 0x89;
const int pushCodeNewAdvert = 0x8A;
const int pushCodeTelemetryResponse = 0x8B;
const int pushCodeBinaryResponse = 0x8C;
// #1028: the radio removed a contact to make room ([code][pub_key 32]), or has
// no room for one ([code]).
const int pushCodeContactDeleted = 0x8F;
const int pushCodeContactsFull = 0x90;
const int pushCodeChannelsChanged =
0x91; // #429 part A: device channel table changed; re-poll getChannels

@ -3009,6 +3009,51 @@
}
},
"contacts_addByKeyFailed": "Could not add the contact. Check the radio connection.",
"contacts_addRadioFull": "{name} was not added. The radio's contact list is full. Remove a contact in Contacts to make room.",
"@contacts_addRadioFull": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"contacts_addRadioRefused": "{name} was not added. The radio didn't accept it (error {code}).",
"@contacts_addRadioRefused": {
"placeholders": {
"name": {
"type": "String"
},
"code": {
"type": "int"
}
}
},
"contacts_addNoReply": "{name} was not added. The radio didn't respond.",
"@contacts_addNoReply": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"contacts_radioFullBanner": "The radio's contact list is full. New contacts can't be added until you remove one.",
"contacts_radioRemovedBanner": "The radio removed {name} to make room for a new contact. Your messages with {name} are kept.",
"@contacts_radioRemovedBanner": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"chat_sendRefusedNotFound": "Not sent: this contact isn't on the radio. Add it again to message it.",
"chat_sendRefused": "Not sent: the radio didn't accept it (error {code}).",
"@chat_sendRefused": {
"placeholders": {
"code": {
"type": "int"
}
}
},
"contacts_myContactQr": "My contact QR",
"contacts_myContactQrInstructions": "Have them scan this, or send them the link below. It works even if they have never heard your advert.",
"contacts_contactLinkCopied": "Contact link copied",

@ -8500,6 +8500,48 @@ abstract class AppLocalizations {
/// **'Could not add the contact. Check the radio connection.'**
String get contacts_addByKeyFailed;
/// No description provided for @contacts_addRadioFull.
///
/// In en, this message translates to:
/// **'{name} was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.'**
String contacts_addRadioFull(String name);
/// No description provided for @contacts_addRadioRefused.
///
/// In en, this message translates to:
/// **'{name} was not added. The radio didn\'t accept it (error {code}).'**
String contacts_addRadioRefused(String name, int code);
/// No description provided for @contacts_addNoReply.
///
/// In en, this message translates to:
/// **'{name} was not added. The radio didn\'t respond.'**
String contacts_addNoReply(String name);
/// No description provided for @contacts_radioFullBanner.
///
/// In en, this message translates to:
/// **'The radio\'s contact list is full. New contacts can\'t be added until you remove one.'**
String get contacts_radioFullBanner;
/// No description provided for @contacts_radioRemovedBanner.
///
/// In en, this message translates to:
/// **'The radio removed {name} to make room for a new contact. Your messages with {name} are kept.'**
String contacts_radioRemovedBanner(String name);
/// No description provided for @chat_sendRefusedNotFound.
///
/// In en, this message translates to:
/// **'Not sent: this contact isn\'t on the radio. Add it again to message it.'**
String get chat_sendRefusedNotFound;
/// No description provided for @chat_sendRefused.
///
/// In en, this message translates to:
/// **'Not sent: the radio didn\'t accept it (error {code}).'**
String chat_sendRefused(int code);
/// No description provided for @contacts_myContactQr.
///
/// In en, this message translates to:

@ -5035,6 +5035,39 @@ class AppLocalizationsBg extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5047,6 +5047,39 @@ class AppLocalizationsDe extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -4969,6 +4969,39 @@ class AppLocalizationsEn extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5036,6 +5036,39 @@ class AppLocalizationsEs extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5058,6 +5058,39 @@ class AppLocalizationsFr extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5053,6 +5053,39 @@ class AppLocalizationsHu extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5041,6 +5041,39 @@ class AppLocalizationsIt extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -4838,6 +4838,39 @@ class AppLocalizationsJa extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -4840,6 +4840,39 @@ class AppLocalizationsKo extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5021,6 +5021,39 @@ class AppLocalizationsNl extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5051,6 +5051,39 @@ class AppLocalizationsPl extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5033,6 +5033,39 @@ class AppLocalizationsPt extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5043,6 +5043,39 @@ class AppLocalizationsRu extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5017,6 +5017,39 @@ class AppLocalizationsSk extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5011,6 +5011,39 @@ class AppLocalizationsSl extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -4990,6 +4990,39 @@ class AppLocalizationsSv extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -5042,6 +5042,39 @@ class AppLocalizationsUk extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -4741,6 +4741,39 @@ class AppLocalizationsZh extends AppLocalizations {
String get contacts_addByKeyFailed =>
'Could not add the contact. Check the radio connection.';
@override
String contacts_addRadioFull(String name) {
return '$name was not added. The radio\'s contact list is full. Remove a contact in Contacts to make room.';
}
@override
String contacts_addRadioRefused(String name, int code) {
return '$name was not added. The radio didn\'t accept it (error $code).';
}
@override
String contacts_addNoReply(String name) {
return '$name was not added. The radio didn\'t respond.';
}
@override
String get contacts_radioFullBanner =>
'The radio\'s contact list is full. New contacts can\'t be added until you remove one.';
@override
String contacts_radioRemovedBanner(String name) {
return 'The radio removed $name to make room for a new contact. Your messages with $name are kept.';
}
@override
String get chat_sendRefusedNotFound =>
'Not sent: this contact isn\'t on the radio. Add it again to message it.';
@override
String chat_sendRefused(int code) {
return 'Not sent: the radio didn\'t accept it (error $code).';
}
@override
String get contacts_myContactQr => 'My contact QR';

@ -67,6 +67,11 @@ class Message {
/// screen's "direct (routed)" vs "flood, N hops" label. (#438)
final bool? isFloodRoute;
/// The radio's error code when it refused this outgoing message outright
/// (RESP_CODE_ERR instead of RESP_CODE_SENT), so a failed bubble can say
/// why. Null otherwise. (#1028)
final int? radioErrorCode;
Message({
required this.senderKey,
required this.text,
@ -97,6 +102,7 @@ class Message {
this.snr,
this.rssi,
this.isFloodRoute,
this.radioErrorCode,
}) : messageId =
messageId ??
'${timestamp.millisecondsSinceEpoch}_${pubKeyToHex(senderKey)}_${text.hashCode}',
@ -133,6 +139,7 @@ class Message {
double? snr,
int? rssi,
bool? isFloodRoute,
Object? radioErrorCode = _unset,
}) {
return Message(
senderKey: senderKey,
@ -173,6 +180,12 @@ class Message {
snr: snr ?? this.snr,
rssi: rssi ?? this.rssi,
isFloodRoute: isFloodRoute ?? this.isFloodRoute,
// A resend moves the status off failed, and the old reason goes with it.
radioErrorCode: radioErrorCode == _unset
? (status == null || status == MessageStatus.failed
? this.radioErrorCode
: null)
: radioErrorCode as int?,
);
}

@ -32,6 +32,7 @@ import '../services/corescope_service.dart';
import '../services/region_discovery_service.dart';
import '../widgets/channel_region_scope_dialog.dart';
import '../widgets/channel_notify_mode.dart';
import '../widgets/contact_add_feedback.dart';
import '../widgets/radio_channel_notify.dart';
import '../widgets/radio_tone.dart';
import '../services/block_service.dart';
@ -940,8 +941,9 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
_showSenderError(l10n.channel_senderAddNotConnected);
return;
}
final ContactAddResult result;
try {
await connector.importDiscoveredContact(candidate);
result = await connector.importDiscoveredContact(candidate);
} catch (e) {
appLogger.error('Adding channel sender ${candidate.name} failed: $e');
if (!mounted) return;
@ -949,10 +951,14 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
return;
}
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.discoveredContacts_contactAdded),
);
if (result.added) {
showDismissibleSnackBar(
context,
content: Text(l10n.discoveredContacts_contactAdded),
);
return;
}
showContactAddResult(context, result, candidate.name);
}
void _showSenderError(String message) {

@ -2048,6 +2048,16 @@ class _MessageBubble extends StatelessWidget {
],
),
),
if (isFailed && message.radioErrorCode != null)
Padding(
padding: const EdgeInsets.only(top: 2),
child: Text(
message.radioErrorCode == errCodeNotFound
? context.l10n.chat_sendRefusedNotFound
: context.l10n.chat_sendRefused(message.radioErrorCode!),
style: TextStyle(fontSize: 11, color: colorScheme.error),
),
),
if (message.reactions.isNotEmpty) ...[
const SizedBox(height: 4),
Padding(

@ -725,8 +725,26 @@ class _ContactsScreenState extends State<ContactsScreen>
120.0,
); //two 48px icon buttons + 1px divider
final notice = connector.contactTableNotice;
return Column(
children: [
if (notice != null)
MaterialBanner(
leading: const Icon(Icons.warning_amber_rounded),
content: Text(
notice.removedName != null
? context.l10n.contacts_radioRemovedBanner(
notice.removedName!,
)
: context.l10n.contacts_radioFullBanner,
),
actions: [
TextButton(
onPressed: connector.dismissContactTableNotice,
child: Text(context.l10n.common_dismiss),
),
],
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(

@ -13,6 +13,7 @@ import '../utils/platform_info.dart';
import '../widgets/app_bar.dart';
import '../widgets/list_filter_widget.dart';
import '../widgets/blocked_badge.dart';
import '../widgets/contact_add_feedback.dart';
import '../services/block_service.dart';
import '../helpers/snack_bar_builder.dart';
@ -193,7 +194,11 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
),
),
onTap: () {
connector.importDiscoveredContact(contact);
importDiscoveredContactWithFeedback(
context,
connector,
contact,
);
},
onLongPress: () =>
_showContactContextMenu(contact, connector),
@ -269,7 +274,7 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
switch (action) {
case 'import_contact':
connector.importDiscoveredContact(contact);
importDiscoveredContactWithFeedback(context, connector, contact);
break;
case 'copy_contact':
if (contact.rawPacket == null) return;

@ -24,6 +24,7 @@ import '../services/map_tile_cache_service.dart';
import '../utils/contact_search.dart';
import '../utils/route_transitions.dart';
import '../widgets/app_shell.dart';
import '../widgets/contact_add_feedback.dart';
import '../widgets/map_layer_panel.dart';
import '../widgets/sync_progress_overlay.dart';
import '../icons/los_icon.dart';
@ -1589,7 +1590,11 @@ class _MapScreenState extends State<MapScreen> {
TextButton(
onPressed: () {
if (!contact.isActive) {
connector.importDiscoveredContact(contact);
importDiscoveredContactWithFeedback(
context,
connector,
contact,
);
}
final unread = connector.getUnreadCountForContactKey(
contact.publicKeyHex,
@ -1611,7 +1616,11 @@ class _MapScreenState extends State<MapScreen> {
TextButton(
onPressed: () {
if (!contact.isActive) {
connector.importDiscoveredContact(contact);
importDiscoveredContactWithFeedback(
context,
connector,
contact,
);
}
Navigator.pop(dialogContext);
_showRepeaterLogin(context, contact);
@ -1622,7 +1631,11 @@ class _MapScreenState extends State<MapScreen> {
TextButton(
onPressed: () {
if (!contact.isActive) {
connector.importDiscoveredContact(contact);
importDiscoveredContactWithFeedback(
context,
connector,
contact,
);
}
Navigator.pop(dialogContext);
_showRoomLogin(context, contact);

@ -391,6 +391,45 @@ class MessageRetryService extends ChangeNotifier {
_onMessageResolved(messageId, contact.publicKeyHex);
}
/// The radio answered a DM send with RESP_CODE_ERR instead of RESP_CODE_SENT,
/// for example NOT_FOUND when it does not hold the contact. A retry cannot
/// succeed, so the message fails now and keeps the reason. Matched only when
/// exactly one send is waiting, as [_adoptUnpredictedSentHash] does. (#1028)
bool failAwaitingSendOnRadioError(int errCode) {
final awaiting = _sendsAwaitingConfirmation;
if (awaiting.length != 1) {
if (awaiting.isNotEmpty) {
_config?.debugLogService?.warn(
'Radio error $errCode with ${awaiting.length} sends waiting; '
'cannot tell which it refused',
tag: 'AckHash',
);
}
return false;
}
final messageId = awaiting.first;
final message = _pendingMessages[messageId];
final contact = _pendingContacts[messageId];
if (message == null || contact == null) return false;
_sentConfirmationTimers.remove(messageId)?.cancel();
_expectedHashToMessageId.removeWhere((_, id) => id == messageId);
final failed = message.copyWith(
status: MessageStatus.failed,
radioErrorCode: errCode,
);
_pendingMessages[messageId] = failed;
_config?.updateMessage(failed);
_config?.debugLogService?.warn(
'Radio refused the message to ${contact.name} (error $errCode), '
'marking send failed',
tag: 'AckHash',
);
notifyListeners();
_onMessageResolved(messageId, contact.publicKeyHex);
return true;
}
/// Message ids whose send reached the radio but whose RESP_CODE_SENT has not
/// arrived yet.
List<String> get _sendsAwaitingConfirmation => _sentConfirmationTimers.keys

@ -278,6 +278,7 @@ class MessageStore {
'snr': msg.snr,
'rssi': msg.rssi,
'isFloodRoute': msg.isFloodRoute,
'radioErrorCode': msg.radioErrorCode,
};
}
@ -343,6 +344,7 @@ class MessageStore {
snr: (json['snr'] as num?)?.toDouble(),
rssi: json['rssi'] as int?,
isFloodRoute: json['isFloodRoute'] as bool?,
radioErrorCode: json['radioErrorCode'] as int?,
);
}
}

@ -4,9 +4,9 @@ import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../l10n/l10n.dart';
import '../helpers/snack_bar_builder.dart';
import '../models/contact.dart';
import '../screens/contact_qr_scanner_screen.dart';
import 'contact_add_feedback.dart';
/// Adds a contact from an identity alone: a public key, a name and a type.
///
@ -130,18 +130,11 @@ class _AddContactByKeyDialogState extends State<_AddContactByKeyDialog> {
setState(() => _submitting = true);
final connector = Provider.of<MeshCoreConnector>(context, listen: false);
final added = await connector.addContactByKey(stub);
final result = await connector.addContactByKey(stub);
if (!mounted) return;
Navigator.of(context).pop();
showDismissibleSnackBar(
context,
content: Text(
added
? l10n.contacts_addByKeyAdded(stub.name)
: l10n.contacts_addByKeyFailed,
),
);
showContactAddResult(context, result, stub.name);
}
@override

@ -0,0 +1,42 @@
import 'package:flutter/material.dart';
import '../connector/meshcore_connector.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
/// Tells the user how a contact add ended. A refusal or no reply stays on
/// screen until dismissed: the contact was not added, and they have to know
/// why. (#1028)
void showContactAddResult(
BuildContext context,
ContactAddResult result,
String name,
) {
final l10n = context.l10n;
final String text;
switch (result.outcome) {
case ContactAddOutcome.added:
text = l10n.contacts_addByKeyAdded(name);
case ContactAddOutcome.refused:
text = result.radioFull
? l10n.contacts_addRadioFull(name)
: l10n.contacts_addRadioRefused(name, result.errCode ?? -1);
case ContactAddOutcome.noReply:
text = l10n.contacts_addNoReply(name);
case ContactAddOutcome.notConnected:
text = l10n.contacts_addByKeyFailed;
}
showDismissibleSnackBar(context, content: Text(text), persist: !result.added);
}
/// Adds a contact heard on the mesh and reports the outcome.
Future<void> importDiscoveredContactWithFeedback(
BuildContext context,
MeshCoreConnector connector,
Contact contact,
) async {
final result = await connector.importDiscoveredContact(contact);
if (!context.mounted) return;
showContactAddResult(context, result, contact.name);
}

@ -0,0 +1,207 @@
// #1028: the app kept contacts the radio had refused, and a DM the radio
// refused sat pending for 8 s with no reason.
//
// From the owner's log: CMD_ADD_UPDATE_CONTACT drew ERR 3 (table full), the
// app logged "Added new contact" anyway, and every DM to that contact then
// drew ERR 2 (not found) and was marked failed only when the 8 s timer ran
// out. These tests use only what dev already has, so each one fails there.
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/models/message.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/storage_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:shared_preferences/shared_preferences.dart';
Uint8List _key(int b) => Uint8List.fromList(List<int>.filled(32, b));
Uint8List _psk(int fill) => Uint8List.fromList(List<int>.filled(16, fill));
Contact _contact(int keyByte, String name) => Contact(
publicKey: _key(keyByte),
receivedName: name,
type: advTypeChat,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late OffbandDatabase db;
late MeshCoreConnector connector;
late List<Uint8List> sent;
void ok() => connector.handleFrameForTest([respCodeOk]);
void err(int code) => connector.handleFrameForTest([respCodeErr, code]);
bool holds(int keyByte) => connector.contactsForTest.any(
(c) => c.publicKeyHex == _contact(keyByte, '').publicKeyHex,
);
Future<void> settle([int turns = 25]) async {
for (var i = 0; i < turns; i++) {
await Future<void>.delayed(Duration.zero);
}
}
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
connector = MeshCoreConnector();
connector.contactsForTest.clear();
connector.setConnectedForTest();
sent = [];
connector.sendFrameOverrideForTest = sent.add;
});
tearDown(() async {
await db.close();
BlobStore.clearTestOverride();
});
group('add by key', () {
test('the radio refusing the add (table full) keeps no contact', () async {
final add = connector.addContactByKey(_contact(0x11, 'Alpha'));
await settle(2);
err(3);
await add;
expect(holds(0x11), isFalse);
});
test('the radio confirming the add keeps the contact', () async {
final add = connector.addContactByKey(_contact(0x11, 'Alpha'));
await settle(2);
ok();
await add;
expect(holds(0x11), isTrue);
});
});
group('add from Discovery', () {
test('the radio refusing the add (table full) keeps no contact', () async {
final add = connector.importDiscoveredContact(_contact(0x22, 'Bravo'));
await settle(2);
err(3);
await add;
expect(holds(0x22), isFalse);
});
test('the radio confirming the add keeps the contact', () async {
final add = connector.importDiscoveredContact(_contact(0x22, 'Bravo'));
await settle(2);
ok();
await add;
expect(holds(0x22), isTrue);
});
// The Discovery add never waited for its own reply, so its ERR was taken
// as the answer to whatever command was waiting next.
test('its refusal is not taken as the next command\'s answer', () async {
final add = connector.importDiscoveredContact(_contact(0x22, 'Bravo'));
await settle(2);
final write = connector.setChannel(
3,
'Weather',
_psk(0x22),
refresh: false,
);
await settle(2);
err(3); // the radio refuses the add
ok(); // and accepts the channel write
await add;
expect(await write, ChannelWrite.ok);
});
});
group('a DM the radio refuses', () {
late Contact bravo;
setUp(() {
connector.initialize(
retryService: MessageRetryService(),
pathHistoryService: PathHistoryService(StorageService()),
);
connector.sendFrameOverrideForTest = sent.add;
bravo = _contact(0x33, 'Charlie');
});
Future<void> untilDmSent() async {
for (var i = 0; i < 500; i++) {
if (sent.any((f) => f.isNotEmpty && f[0] == cmdSendTxtMsg)) return;
await Future<void>.delayed(const Duration(milliseconds: 2));
}
fail('the DM was never sent');
}
MessageStatus? statusOfLast() =>
connector.conversationsForTest[bravo.publicKeyHex]?.last.status;
test('fails at once when the radio answers not found', () async {
await connector.sendMessage(bravo, 'hello');
await untilDmSent();
err(errCodeNotFound);
await settle();
expect(statusOfLast(), MessageStatus.failed);
});
test('is not failed by the radio confirming the send', () async {
await connector.sendMessage(bravo, 'hello');
await untilDmSent();
connector.handleFrameForTest([
respCodeSent,
1,
0x01, 0x02, 0x03, 0x04, // expected ack hash
0x10, 0x27, 0x00, 0x00, // timeout 10000 ms
]);
await settle();
expect(statusOfLast(), isNot(MessageStatus.failed));
});
});
group('the radio removing a contact to make room', () {
test('removes it from the app\'s contacts too', () async {
final add = connector.addContactByKey(_contact(0x44, 'Delta'));
await settle(2);
ok();
await add;
expect(holds(0x44), isTrue);
connector.handleFrameForTest([0x8F, ..._key(0x44)]);
await settle();
expect(holds(0x44), isFalse);
});
test('leaves every other contact alone', () async {
for (final b in [0x44, 0x55]) {
final add = connector.addContactByKey(_contact(b, 'N$b'));
await settle(2);
ok();
await add;
}
connector.handleFrameForTest([0x8F, ..._key(0x44)]);
await settle();
expect(holds(0x55), isTrue);
});
});
}

@ -0,0 +1,268 @@
// #1028: what the user is told when the radio refuses, ignores, or makes room
// for a contact, and why a refused DM failed. contact_add_confirm_test.dart
// covers the behavior with dev's API; this file covers what #1028 adds.
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/models/message.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/storage_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:shared_preferences/shared_preferences.dart';
Uint8List _key(int b) => Uint8List.fromList(List<int>.filled(32, b));
Contact _contact(int keyByte, String name) => Contact(
publicKey: _key(keyByte),
receivedName: name,
type: advTypeChat,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
);
Uint8List _u32(int v) =>
Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little);
Uint8List _contactFrame(int keyByte, String name) {
final b = BytesBuilder()
..addByte(respCodeContact)
..add(_key(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();
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late OffbandDatabase db;
late MeshCoreConnector connector;
late List<Uint8List> sent;
void ok() => connector.handleFrameForTest([respCodeOk]);
void err(int code) => connector.handleFrameForTest([respCodeErr, code]);
Future<void> settle([int turns = 25]) async {
for (var i = 0; i < turns; i++) {
await Future<void>.delayed(Duration.zero);
}
}
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
connector = MeshCoreConnector();
connector.contactsForTest.clear();
connector.setConnectedForTest();
sent = [];
connector.sendFrameOverrideForTest = sent.add;
});
tearDown(() async {
await db.close();
BlobStore.clearTestOverride();
});
group('the add result says what the radio did', () {
test('OK is added', () async {
final add = connector.addContactByKey(_contact(0x11, 'Alpha'));
await settle(2);
ok();
final result = await add;
expect(result.outcome, ContactAddOutcome.added);
expect(connector.contactTableNotice, isNull);
});
test('table full is refused, says full, and raises the notice', () async {
final add = connector.addContactByKey(_contact(0x11, 'Alpha'));
await settle(2);
err(errCodeTableFull);
final result = await add;
expect(result.outcome, ContactAddOutcome.refused);
expect(result.radioFull, isTrue);
expect(connector.contactTableNotice, isNotNull);
expect(connector.contactTableNotice!.removedName, isNull);
});
test('another error is refused with its code, and is not "full"', () async {
final add = connector.importDiscoveredContact(_contact(0x11, 'Alpha'));
await settle(2);
err(errCodeIllegalArg);
final result = await add;
expect(result.outcome, ContactAddOutcome.refused);
expect(result.errCode, errCodeIllegalArg);
expect(result.radioFull, isFalse);
expect(connector.contactTableNotice, isNull);
});
test('no answer is noReply and keeps no contact', () async {
connector.contactAddReplyTimeout = const Duration(milliseconds: 20);
final result = await connector.addContactByKey(_contact(0x11, 'Alpha'));
expect(result.outcome, ContactAddOutcome.noReply);
expect(connector.contactsForTest, isEmpty);
});
test('a timed-out add cannot take the next command\'s reply', () async {
connector.contactAddReplyTimeout = const Duration(milliseconds: 20);
await connector.addContactByKey(_contact(0x11, 'Alpha'));
connector.contactAddReplyTimeout = const Duration(seconds: 5);
final second = connector.addContactByKey(_contact(0x22, 'Bravo'));
await settle(2);
ok();
expect((await second).outcome, ContactAddOutcome.added);
});
test('disconnected sends nothing', () async {
final fresh = MeshCoreConnector();
fresh.sendFrameOverrideForTest = sent.add;
final result = await fresh.addContactByKey(_contact(0x11, 'Alpha'));
expect(result.outcome, ContactAddOutcome.notConnected);
expect(sent, isEmpty);
});
});
group('the contact table notice', () {
test('names the contact the radio removed to make room', () async {
final add = connector.addContactByKey(_contact(0x44, 'Delta'));
await settle(2);
ok();
await add;
connector.handleFrameForTest([pushCodeContactDeleted, ..._key(0x44)]);
expect(connector.contactTableNotice?.removedName, 'Delta');
});
test('a removal of a contact the app did not hold raises nothing', () {
connector.handleFrameForTest([pushCodeContactDeleted, ..._key(0x99)]);
expect(connector.contactTableNotice, isNull);
});
test('the radio reporting itself full raises it', () {
connector.handleFrameForTest([pushCodeContactsFull]);
expect(connector.contactTableNotice, isNotNull);
});
test('a complete sync at capacity raises it', () async {
connector.maxContactsForTest = 2;
await connector.getContacts();
connector.handleFrameForTest([respCodeContactsStart, ..._u32(2)]);
connector.handleFrameForTest(_contactFrame(0x11, 'Alpha'));
connector.handleFrameForTest(_contactFrame(0x22, 'Bravo'));
connector.handleFrameForTest([respCodeEndOfContacts, ..._u32(0)]);
await settle();
expect(connector.contactTableNotice, isNotNull);
});
test('a complete sync below capacity raises nothing', () async {
connector.maxContactsForTest = 3;
await connector.getContacts();
connector.handleFrameForTest([respCodeContactsStart, ..._u32(2)]);
connector.handleFrameForTest(_contactFrame(0x11, 'Alpha'));
connector.handleFrameForTest(_contactFrame(0x22, 'Bravo'));
connector.handleFrameForTest([respCodeEndOfContacts, ..._u32(0)]);
await settle();
expect(connector.contactTableNotice, isNull);
});
test('dismissing clears it', () {
connector.handleFrameForTest([pushCodeContactsFull]);
connector.dismissContactTableNotice();
expect(connector.contactTableNotice, isNull);
});
});
group('a refused DM', () {
late Contact charlie;
setUp(() {
connector.initialize(
retryService: MessageRetryService(),
pathHistoryService: PathHistoryService(StorageService()),
);
connector.sendFrameOverrideForTest = sent.add;
charlie = _contact(0x33, 'Charlie');
});
Future<void> untilDmsSent(int count) async {
for (var i = 0; i < 500; i++) {
if (sent.where((f) => f.isNotEmpty && f[0] == cmdSendTxtMsg).length >=
count) {
return;
}
await Future<void>.delayed(const Duration(milliseconds: 2));
}
fail('the DM was never sent');
}
Message? last(Contact c) =>
connector.conversationsForTest[c.publicKeyHex]?.last;
test('keeps the radio\'s reason', () async {
await connector.sendMessage(charlie, 'hello');
await untilDmsSent(1);
err(errCodeNotFound);
await settle();
expect(last(charlie)?.radioErrorCode, errCodeNotFound);
});
test('an ERR during a contact sync is not taken as the DM\'s', () async {
await connector.sendMessage(charlie, 'hello');
await untilDmsSent(1);
await connector.getContacts();
err(errCodeNotFound);
await settle();
expect(last(charlie)?.status, MessageStatus.pending);
});
test('with two DMs waiting, an ERR fails neither', () async {
final delta = _contact(0x44, 'Delta');
await connector.sendMessage(charlie, 'one');
await connector.sendMessage(delta, 'two');
await untilDmsSent(2);
err(errCodeNotFound);
await settle();
expect(last(charlie)?.status, MessageStatus.pending);
expect(last(delta)?.status, MessageStatus.pending);
});
});
group('the stored reason', () {
final failed = Message(
senderKey: _key(0x33),
text: 'hello',
timestamp: DateTime.utc(2026, 11, 24),
isOutgoing: true,
status: MessageStatus.failed,
radioErrorCode: errCodeNotFound,
);
test('a resend clears it', () {
final resent = failed.copyWith(status: MessageStatus.pending);
expect(resent.radioErrorCode, isNull);
});
test('an unrelated update keeps it', () {
expect(failed.copyWith(retryCount: 1).radioErrorCode, errCodeNotFound);
});
});
}

@ -18,12 +18,17 @@ import 'package:meshcore_open/widgets/add_contact_by_key_dialog.dart';
const _key = '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff';
class _CapturingConn extends MeshCoreConnector {
_CapturingConn({
this.result = const ContactAddResult(ContactAddOutcome.added),
});
final ContactAddResult result;
final List<Contact> added = [];
@override
Future<bool> addContactByKey(Contact stub) async {
Future<ContactAddResult> addContactByKey(Contact stub) async {
added.add(stub);
return true;
return result;
}
}
@ -180,6 +185,46 @@ void main() {
expect(stub.lastSeen, DateTime.fromMillisecondsSinceEpoch(0));
});
// #1028: the radio's answer reaches the user, and a refusal stays up.
for (final (label, result, text) in [
(
'full',
const ContactAddResult(
ContactAddOutcome.refused,
errCode: errCodeTableFull,
),
"Bob was not added. The radio's contact list is full.",
),
(
'refused',
const ContactAddResult(
ContactAddOutcome.refused,
errCode: errCodeIllegalArg,
),
"Bob was not added. The radio didn't accept it (error 6).",
),
(
'no reply',
const ContactAddResult(ContactAddOutcome.noReply),
"Bob was not added. The radio didn't respond.",
),
]) {
testWidgets('a $label add says so and stays on screen', (tester) async {
final conn = _CapturingConn(result: result);
await _open(tester, conn);
await tester.enterText(find.byType(TextField).first, _key);
await tester.enterText(find.byType(TextField).last, 'Bob');
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(FilledButton, 'Add'));
await tester.pumpAndSettle();
await tester.pump(const Duration(seconds: 30));
expect(find.textContaining(text), findsOneWidget);
expect(find.textContaining('Added Bob'), findsNothing);
});
}
testWidgets('a missing name falls back rather than blocking the add', (
tester,
) async {

@ -269,6 +269,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -683,6 +690,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -1097,6 +1111,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -1511,6 +1532,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -1925,6 +1953,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -2339,6 +2374,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -2753,6 +2795,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -3167,6 +3216,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -3581,6 +3637,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -3995,6 +4058,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -4409,6 +4479,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -4823,6 +4900,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -5237,6 +5321,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -5651,6 +5742,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -6065,6 +6163,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -6479,6 +6584,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",
@ -6893,6 +7005,13 @@
"contacts_addByKeyUnverifiedNote",
"contacts_addByKeyAdded",
"contacts_addByKeyFailed",
"contacts_addRadioFull",
"contacts_addRadioRefused",
"contacts_addNoReply",
"contacts_radioFullBanner",
"contacts_radioRemovedBanner",
"chat_sendRefusedNotFound",
"chat_sendRefused",
"contacts_myContactQr",
"contacts_myContactQrInstructions",
"contacts_contactLinkCopied",

Loading…
Cancel
Save

Powered by TurnKey Linux.