Fix review findings, add default flood scope, and address recent issues

Review fixes:
- Keep stored message history beyond the 200-message window; stop
  messages leaking between radios; reset link/session state on disconnect
- Accept firmware's 176-byte RX frames over USB/TCP
- Hold APP_START during contact sync; contact-sync watchdog; replay DMs
  from not-yet-known senders; tombstone late command replies; finish
  channel sync on ERR_NOT_FOUND; fail region-scoped sends cleanly
- DM retry watchdog when RESP_CODE_SENT never arrives; late repeater CLI
  replies; ACK hash collisions; UTF-8-safe name truncation
- Image pipeline: delete-during-decode, lifecycle cancels, decoder memory
  release, entry cap, dead worker recovery, atomic model writes
- Storage: deterministic reaction hash across web/native, Smaz
  double-decode, per-entry parsing, per-radio path history and regions,
  review-mode data isolation
- UI: safe channel slot selection, byte-length name limits, double-send
  guard, mounted checks, localized hardcoded strings
- Skip persisted-store reload on repeat SELF_INFO

Features:
- Radio default flood scope (firmware ver 11+) and explicit unscoped
  sends (ver 12+)
- Scan for nearby nodes (#570)
- Optional distinct first-hop repeater counting for channel resend (#589)
- Optional region next to hop count (#580)

Issues:
- Message text follows system font size (#569)
- Repeater/room password field accepts 20 chars (#576)
- TCP auto-reconnect and keepalive (#571)
- Order feeds by local receive time; flag future timestamps (#584)
- Coding rate help text (#568), French "Favoris" (#575)
- iOS/macOS app badge now clears

Translations for all new strings in every locale.
This commit is contained in:
zjs81 committed 2026-10-11 01:25:31 -07:00
1 parent a64a33d0c0
commit 25f197c979
120 files changed
+10424 -687

No files matched your search

+131 -29
View File
@@ -1,8 +1,10 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:meshcore_open/utils/app_logger.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/channel_message.dart';
import '../models/message.dart' show legacyAwareReceivedAt;
import '../models/translation_support.dart';
import '../helpers/smaz.dart';
import 'legacy_key_migration.dart';
@@ -17,7 +19,20 @@ class ChannelMessageStore {
String get keyFor => '$_keyPrefix$publicKeyHex';
/// Save messages for a specific channel
/// Upper bound on persisted messages per channel. The oldest entries
/// beyond it are dropped on save.
static const int maxStoredMessages = 1000;
/// Encoded entries persisted ahead of the connector's in-memory window,
/// keyed by scoped storage key. A missing entry means the window has not
/// been reconciled with storage yet, so the next save keeps what is already
/// stored instead of replacing it. Shared across instances so a store
/// created by a screen to clear a key also resets the connector's view.
static final Map<String, List<String>> _archived = {};
/// Save messages for a specific channel: [messages] is the in-memory
/// window (oldest first) and is written after the archived entries that
/// sit ahead of it in storage.
Future<void> saveChannelMessages(
int channelIndex,
List<ChannelMessage> messages,
@@ -30,12 +45,99 @@ class ChannelMessageStore {
}
final prefs = PrefsManager.instance;
final key = '$keyFor$channelIndex';
final visibleJson = messages.map(_messageToJson).toList();
final archived =
_archived[key] ??
_unreconciledArchive(_readStored(prefs, channelIndex), visibleJson);
final overflow = archived.length + visibleJson.length - maxStoredMessages;
if (overflow > 0) {
archived.removeRange(0, overflow.clamp(0, archived.length));
}
_archived[key] = archived;
final entries = [...archived, ...visibleJson.map(jsonEncode)];
await prefs.setString(key, '[${entries.join(',')}]');
}
// Convert messages to JSON
final jsonList = messages.map((msg) => _messageToJson(msg)).toList();
final jsonString = jsonEncode(jsonList);
/// Records [olderMessages] as the stored entries that precede the
/// in-memory window for [channelIndex].
void setArchived(int channelIndex, List<ChannelMessage> olderMessages) {
_archived['$keyFor$channelIndex'] = olderMessages
.map((message) => jsonEncode(_messageToJson(message)))
.toList();
}
await prefs.setString(key, jsonString);
/// Number of stored entries ahead of the in-memory window, or null when
/// the window has not been reconciled with storage.
int? archivedCount(int channelIndex) =>
_archived['$keyFor$channelIndex']?.length;
/// Removes the newest [count] archived entries after they were paged back
/// into the in-memory window.
void unarchiveNewest(int channelIndex, int count) {
final archived = _archived['$keyFor$channelIndex'];
if (archived == null || count <= 0) return;
archived.removeRange(
(archived.length - count).clamp(0, archived.length),
archived.length,
);
}
/// Drops the archive bookkeeping, for one channel or all of them, when the
/// matching in-memory window is discarded.
void forgetArchive([int? channelIndex]) {
if (channelIndex == null) {
_archived.clear();
} else {
_archived.remove('$keyFor$channelIndex');
}
}
List<String> _unreconciledArchive(
String? storedJson,
List<Map<String, dynamic>> visibleJson,
) {
if (storedJson == null || storedJson.isEmpty) return [];
final List<dynamic> stored;
try {
stored = jsonDecode(storedJson) as List<dynamic>;
} catch (_) {
return [];
}
final visibleKeys = visibleJson.map(_storedMergeKey).toSet();
return [
for (final entry in stored)
if (entry is Map<String, dynamic> &&
!visibleKeys.contains(_storedMergeKey(entry)))
jsonEncode(entry),
];
}
static String _storedMergeKey(Map<String, dynamic> json) {
final messageId = json['messageId'];
if (messageId is String && messageId.isNotEmpty) return 'id:$messageId';
return 'fallback:${json['timestamp']}:${json['senderName']}:${json['text']}';
}
/// Reads the stored JSON for [channelIndex], migrating the legacy unscoped
/// key on first access.
String? _readStored(SharedPreferences prefs, int channelIndex) {
final key = '$keyFor$channelIndex';
final oldKey = '$_keyPrefix$channelIndex';
final jsonString = prefs.getString(key);
if ((jsonString == null || jsonString.isEmpty) &&
canMigrateLegacyKeys(publicKeyHex)) {
// Attempt migration from legacy unscoped key on first load
final legacyJsonString = prefs.getString(oldKey);
prefs.remove(oldKey);
if (legacyJsonString != null && legacyJsonString.isNotEmpty) {
appLogger.info(
'Migrating channel messages from legacy key $oldKey to scoped key $key',
);
prefs.setString(key, legacyJsonString);
return legacyJsonString;
}
}
return jsonString;
}
/// Load messages for a specific channel
@@ -47,23 +149,7 @@ class ChannelMessageStore {
return [];
}
final prefs = PrefsManager.instance;
final key = '$keyFor$channelIndex';
final oldKey = '$_keyPrefix$channelIndex';
String? jsonString = prefs.getString(key);
if ((jsonString == null || jsonString.isEmpty) &&
canMigrateLegacyKeys(publicKeyHex)) {
// Attempt migration from legacy unscoped key on first load
final legacyJsonString = prefs.getString(oldKey);
prefs.remove(oldKey);
if (legacyJsonString != null && legacyJsonString.isNotEmpty) {
appLogger.info(
'Migrating channel messages from legacy key $oldKey to scoped key $key',
);
await prefs.setString(key, legacyJsonString);
jsonString = legacyJsonString;
}
}
String? jsonString = _readStored(prefs, channelIndex);
if (jsonString == null || jsonString.isEmpty) {
jsonString = prefs.getString(keyFor);
}
@@ -94,13 +180,15 @@ class ChannelMessageStore {
Future<void> clearChannelMessages(int channelIndex) async {
final prefs = PrefsManager.instance;
final key = '$keyFor$channelIndex';
_archived[key] = [];
await prefs.remove(key);
}
/// Clear all channel messages
Future<void> clearAllChannelMessages() async {
final prefs = PrefsManager.instance;
final keys = prefs.getKeys().where((k) => k.startsWith(keyFor));
final keys = prefs.getKeys().where((k) => k.startsWith(keyFor)).toList();
_archived.clear();
for (var key in keys) {
await prefs.remove(key);
}
@@ -118,6 +206,7 @@ class ChannelMessageStore {
'translationStatus': msg.translationStatus.value,
'translationModelId': msg.translationModelId,
'timestamp': msg.timestamp.millisecondsSinceEpoch,
'receivedAt': msg.receivedAt.millisecondsSinceEpoch,
'isOutgoing': msg.isOutgoing,
'status': msg.status.index,
'channelIndex': msg.channelIndex,
@@ -134,13 +223,18 @@ class ChannelMessageStore {
'replyToSenderName': msg.replyToSenderName,
'replyToText': msg.replyToText,
'reactions': msg.reactions,
// `text` is stored decoded; legacy records without this flag may still
// hold a Smaz payload.
'plainText': true,
};
}
/// Convert JSON map to ChannelMessage
ChannelMessage _messageFromJson(Map<String, dynamic> json) {
final rawText = json['text'] as String;
final decodedText = Smaz.tryDecodePrefixed(rawText) ?? rawText;
final decodedText = json['plainText'] == true
? rawText
: (Smaz.tryDecodePrefixed(rawText) ?? rawText);
final rawPathLength = json['pathLength'] as int?;
final rawPathBytes = json['pathBytes'] != null
@@ -187,12 +281,9 @@ class ChannelMessageStore {
),
translationModelId: json['translationModelId'] as String?,
timestamp: DateTime.fromMillisecondsSinceEpoch(json['timestamp'] as int),
receivedAt: legacyAwareReceivedAt(json),
isOutgoing: json['isOutgoing'] as bool? ?? false,
status:
ChannelMessageStatus.values.elementAtOrNull(
json['status'] as int? ?? -1,
) ??
ChannelMessageStatus.failed,
status: _statusAt(json['status']) ?? ChannelMessageStatus.failed,
repeatCount: (json['repeatCount'] as int?) ?? 0,
pathLength: decodedPathLength,
pathHashWidth: decodedPathHashWidth,
@@ -248,4 +339,15 @@ class ChannelMessageStore {
.toList(),
);
}
/// Out-of-range or non-int values yield null; `elementAtOrNull` throws on
/// negative indexes.
static ChannelMessageStatus? _statusAt(Object? value) {
if (value is! int ||
value < 0 ||
value >= ChannelMessageStatus.values.length) {
return null;
}
return ChannelMessageStatus.values[value];
}
}
+22 -1
View File
@@ -3,6 +3,7 @@ import 'prefs_manager.dart';
class ChannelRegionStore {
static const String _keyPrefix = 'channel_region_';
static const String _defaultKeyPrefix = 'default_region_';
String publicKeyHex = '';
set setPublicKeyHex(String value) =>
@@ -10,7 +11,27 @@ class ChannelRegionStore {
String get keyFor => '$_keyPrefix$publicKeyHex';
String get _defaultKey => 'default_region_$publicKeyHex';
String get _defaultKey => '$_defaultKeyPrefix$publicKeyHex';
/// Clears every channel and default region assignment equal to [region],
/// across all radios. The region list is app-wide, so a deleted region must
/// not stay assigned on radios other than the connected one.
static Future<void> clearRegionEverywhere(String region) async {
final prefs = PrefsManager.instance;
final keys = prefs
.getKeys()
.where(
(key) =>
key.startsWith(_keyPrefix) || key.startsWith(_defaultKeyPrefix),
)
.toList();
for (final key in keys) {
final value = prefs.get(key);
if (value is String && value == region) {
await prefs.setString(key, '');
}
}
}
String loadDefaultRegion() {
if (publicKeyHex.isEmpty) return '';
+13 -5
View File
@@ -42,14 +42,22 @@ class ChannelStore {
return [];
}
final List<dynamic> jsonList;
try {
final jsonList = jsonDecode(jsonString) as List<dynamic>;
return jsonList
.map((entry) => _fromJson(entry as Map<String, dynamic>))
.toList();
} catch (_) {
jsonList = jsonDecode(jsonString) as List<dynamic>;
} catch (e) {
appLogger.warn('Stored channels are unreadable: $e');
return [];
}
final channels = <Channel>[];
for (final entry in jsonList) {
try {
channels.add(_fromJson(entry as Map<String, dynamic>));
} catch (e) {
appLogger.warn('Skipping malformed stored channel: $e');
}
}
return channels;
}
Future<void> saveChannels(List<Channel> channels) async {
+2 -1
View File
@@ -3,6 +3,7 @@ import 'dart:typed_data';
import '../models/contact.dart';
import '../utils/app_logger.dart';
import 'legacy_key_migration.dart';
import 'prefs_manager.dart';
class ContactDiscoveryStore {
@@ -18,7 +19,7 @@ class ContactDiscoveryStore {
if (publicKeyHex.isEmpty) return [];
final prefs = PrefsManager.instance;
var jsonStr = prefs.getString(keyFor);
if (jsonStr == null) {
if (jsonStr == null && canMigrateLegacyKeys(publicKeyHex)) {
jsonStr = prefs.getString(_keyPrefix);
if (jsonStr != null) {
await prefs.setString(keyFor, jsonStr);
+136 -18
View File
@@ -1,5 +1,8 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/message.dart';
import '../models/translation_support.dart';
import '../helpers/smaz.dart';
@@ -16,6 +19,19 @@ class MessageStore {
String get keyFor => '$_keyPrefix$publicKeyHex';
/// Upper bound on persisted messages per conversation. The oldest entries
/// beyond it are dropped on save.
static const int maxStoredMessages = 1000;
/// Encoded entries persisted ahead of the connector's in-memory window,
/// keyed by scoped storage key. A missing entry means the window has not
/// been reconciled with storage yet, so the next save keeps what is already
/// stored instead of replacing it. Shared across instances so a store
/// created by a screen to clear a key also resets the connector's view.
static final Map<String, List<String>> _archived = {};
/// Persists [messages] (the in-memory window, oldest first) after the
/// archived entries that sit ahead of it in storage.
Future<void> saveMessages(
String contactKeyHex,
List<Message> messages,
@@ -26,19 +42,96 @@ class MessageStore {
}
final prefs = PrefsManager.instance;
final key = '$keyFor$contactKeyHex';
final jsonList = messages.map(_messageToJson).toList();
await prefs.setString(key, jsonEncode(jsonList));
final visibleJson = messages.map(_messageToJson).toList();
final archived =
_archived[key] ??
_unreconciledArchive(_readStored(prefs, contactKeyHex), visibleJson);
final overflow = archived.length + visibleJson.length - maxStoredMessages;
if (overflow > 0) {
archived.removeRange(0, overflow.clamp(0, archived.length));
}
_archived[key] = archived;
final entries = [...archived, ...visibleJson.map(jsonEncode)];
await prefs.setString(key, '[${entries.join(',')}]');
}
Future<List<Message>> loadMessages(String contactKeyHex) async {
if (publicKeyHex.isEmpty) {
appLogger.warn('Public key hex is not set. Cannot load messages.');
/// Records [olderMessages] as the stored entries that precede the
/// in-memory window for [contactKeyHex].
void setArchived(String contactKeyHex, List<Message> olderMessages) {
_archived['$keyFor$contactKeyHex'] = olderMessages
.map((message) => jsonEncode(_messageToJson(message)))
.toList();
}
/// Moves [messages], just trimmed from the front of the in-memory window,
/// into the archive so the next save keeps them.
void archive(String contactKeyHex, List<Message> messages) {
final archived = _archived['$keyFor$contactKeyHex'];
// Unreconciled saves keep everything already stored anyway.
if (archived == null) return;
archived.addAll(
messages.map((message) => jsonEncode(_messageToJson(message))),
);
}
/// Number of stored entries ahead of the in-memory window, or null when
/// the window has not been reconciled with storage.
int? archivedCount(String contactKeyHex) =>
_archived['$keyFor$contactKeyHex']?.length;
/// Removes the newest [count] archived entries after they were paged back
/// into the in-memory window.
void unarchiveNewest(String contactKeyHex, int count) {
final archived = _archived['$keyFor$contactKeyHex'];
if (archived == null || count <= 0) return;
archived.removeRange(
(archived.length - count).clamp(0, archived.length),
archived.length,
);
}
/// Drops the archive bookkeeping, for one conversation or all of them,
/// when the matching in-memory window is discarded.
void forgetArchive([String? contactKeyHex]) {
if (contactKeyHex == null) {
_archived.clear();
} else {
_archived.remove('$keyFor$contactKeyHex');
}
}
List<String> _unreconciledArchive(
String? storedJson,
List<Map<String, dynamic>> visibleJson,
) {
if (storedJson == null || storedJson.isEmpty) return [];
final List<dynamic> stored;
try {
stored = jsonDecode(storedJson) as List<dynamic>;
} catch (_) {
return [];
}
final prefs = PrefsManager.instance;
final visibleKeys = visibleJson.map(_storedMergeKey).toSet();
return [
for (final entry in stored)
if (entry is Map<String, dynamic> &&
!visibleKeys.contains(_storedMergeKey(entry)))
jsonEncode(entry),
];
}
static String _storedMergeKey(Map<String, dynamic> json) {
final messageId = json['messageId'];
if (messageId is String && messageId.isNotEmpty) return 'id:$messageId';
return 'fallback:${json['timestamp']}:${json['isOutgoing']}:${json['text']}';
}
/// Reads the stored JSON for [contactKeyHex], migrating the legacy unscoped
/// key on first access.
String? _readStored(SharedPreferences prefs, String contactKeyHex) {
final key = '$keyFor$contactKeyHex';
final oldKey = '$_keyPrefix$contactKeyHex';
String? jsonString = prefs.getString(key);
final jsonString = prefs.getString(key);
if ((jsonString == null || jsonString.isEmpty) &&
canMigrateLegacyKeys(publicKeyHex)) {
// Attempt migration from legacy unscoped key on first load
@@ -48,10 +141,20 @@ class MessageStore {
appLogger.info(
'Migrating messages from legacy key $oldKey to scoped key $key',
);
await prefs.setString(key, legacyJsonString);
jsonString = legacyJsonString;
prefs.setString(key, legacyJsonString);
return legacyJsonString;
}
}
return jsonString;
}
Future<List<Message>> loadMessages(String contactKeyHex) async {
if (publicKeyHex.isEmpty) {
appLogger.warn('Public key hex is not set. Cannot load messages.');
return [];
}
final prefs = PrefsManager.instance;
String? jsonString = _readStored(prefs, contactKeyHex);
if (jsonString == null || jsonString.isEmpty) {
jsonString = prefs.getString(keyFor);
}
@@ -84,6 +187,7 @@ class MessageStore {
}
final prefs = PrefsManager.instance;
final key = '$keyFor$contactKeyHex';
_archived[key] = [];
await prefs.remove(key);
}
@@ -92,6 +196,7 @@ class MessageStore {
'senderKey': base64Encode(msg.senderKey),
'text': msg.text,
'timestamp': msg.timestamp.millisecondsSinceEpoch,
'receivedAt': msg.receivedAt.millisecondsSinceEpoch,
'isOutgoing': msg.isOutgoing,
'isCli': msg.isCli,
'status': msg.status.index,
@@ -116,13 +221,16 @@ class MessageStore {
(key, value) => MapEntry(key, value.index),
),
'fourByteRoomContactKey': base64Encode(msg.fourByteRoomContactKey),
// `text` is stored decoded; legacy records without this flag may still
// hold a Smaz payload.
'plainText': true,
};
}
Message _messageFromJson(Map<String, dynamic> json) {
final rawText = json['text'] as String;
final isCli = json['isCli'] as bool? ?? false;
final decodedText = isCli
final decodedText = isCli || json['plainText'] == true
? rawText
: (Smaz.tryDecodePrefixed(rawText) ?? rawText);
@@ -158,11 +266,10 @@ class MessageStore {
senderKey: Uint8List.fromList(base64Decode(json['senderKey'] as String)),
text: decodedText,
timestamp: DateTime.fromMillisecondsSinceEpoch(json['timestamp'] as int),
receivedAt: legacyAwareReceivedAt(json),
isOutgoing: json['isOutgoing'] as bool? ?? false,
isCli: isCli,
status:
MessageStatus.values.elementAtOrNull(json['status'] as int? ?? -1) ??
MessageStatus.failed,
status: _statusAt(json['status']) ?? MessageStatus.failed,
messageId: json['messageId'] as String?,
originalText: json['originalText'] as String?,
translatedText: json['translatedText'] as String?,
@@ -193,11 +300,13 @@ class MessageStore {
),
) ??
{},
reactionStatuses:
(json['reactionStatuses'] as Map<String, dynamic>?)?.map(
(key, value) => MapEntry(key, MessageStatus.values[value as int]),
) ??
{},
reactionStatuses: <String, MessageStatus>{
for (final entry
in (json['reactionStatuses'] as Map<String, dynamic>? ??
const <String, dynamic>{})
.entries)
entry.key: ?_statusAt(entry.value),
},
fourByteRoomContactKey: json['fourByteRoomContactKey'] != null
? Uint8List.fromList(
base64Decode(json['fourByteRoomContactKey'] as String),
@@ -205,4 +314,13 @@ class MessageStore {
: null,
);
}
/// Out-of-range or non-int values yield null; `elementAtOrNull` throws on
/// negative indexes.
static MessageStatus? _statusAt(Object? value) {
if (value is! int || value < 0 || value >= MessageStatus.values.length) {
return null;
}
return MessageStatus.values[value];
}
}
+6 -15
View File
@@ -1,10 +1,14 @@
import 'package:meshcore_open/storage/channel_region_store.dart';
import 'package:meshcore_open/storage/channel_store.dart';
import 'prefs_manager.dart';
typedef Region = String;
/// Stored region assignment meaning "explicitly no region": floods go out
/// unscoped even when an app or radio default region exists. '!' cannot occur
/// in a region name, so it never collides with a real region.
const Region kUnscopedRegion = '!unscoped';
class RegionStore {
static const String key = 'regions';
String publicKeyHex = '';
@@ -36,20 +40,7 @@ class RegionStore {
Future<void> removeRegion(Region region) async {
final regions = loadRegions();
final channelStore = ChannelStore();
final channelRegionStore = ChannelRegionStore();
channelStore.setPublicKeyHex = publicKeyHex;
channelRegionStore.setPublicKeyHex = publicKeyHex;
for (var channel in await channelStore.loadChannels()) {
var channelRegion = await channelRegionStore.loadRegion(channel.index);
if (channelRegion == region) {
await channelRegionStore.saveRegion(channel.index, '');
}
}
if (channelRegionStore.loadDefaultRegion() == region) {
await channelRegionStore.saveDefaultRegion('');
}
await ChannelRegionStore.clearRegionEverywhere(region);
regions.remove(region);
saveRegions(regions);
}
+13 -3
View File
@@ -54,12 +54,22 @@ class UnreadStore {
return {};
}
final Map<String, dynamic> json;
try {
final json = jsonDecode(jsonString) as Map<String, dynamic>;
return json.map((key, value) => MapEntry(key, value as int));
} catch (_) {
json = jsonDecode(jsonString) as Map<String, dynamic>;
} catch (e) {
appLogger.warn('Stored unread counts are unreadable: $e');
return {};
}
final counts = <String, int>{};
json.forEach((key, value) {
if (value is int) {
counts[key] = value;
} else if (value is num) {
counts[key] = value.toInt();
}
});
return counts;
}
void saveContactUnreadCount(Map<String, int> counts) {