Merge remote-tracking branch 'origin/dev' into fix/usb-serial-nonblocking-close

# Conflicts:
#	pubspec.yaml
This commit is contained in:
zjs81 committed 2026-09-27 11:50:25 -07:00
commit 8b8715cfda
132 files changed
+16943 -3604

No files matched your search

+16
View File
@@ -105,6 +105,10 @@ class AppSettingsService extends ChangeNotifier {
await updateSettings(_settings.copyWith(mapShowGuessedLocations: value));
}
Future<void> setMapClusterNodes(bool value) async {
await updateSettings(_settings.copyWith(mapClusterNodes: value));
}
Future<void> setEnableMessageTracing(bool value) async {
await updateSettings(_settings.copyWith(enableMessageTracing: value));
}
@@ -206,6 +210,18 @@ class AppSettingsService extends ChangeNotifier {
await updateSettings(_settings.copyWith(maxMessageRetries: value));
}
Future<void> setChannelMinHopsEnabled(bool value) async {
await updateSettings(_settings.copyWith(channelMinHopsEnabled: value));
}
Future<void> setChannelMinHops(int value) async {
await updateSettings(_settings.copyWith(channelMinHops: value));
}
Future<void> setChannelMinHopsRetries(int value) async {
await updateSettings(_settings.copyWith(channelMinHopsRetries: value));
}
Future<void> setThemeMode(String value) async {
await updateSettings(_settings.copyWith(themeMode: value));
}
+5
View File
@@ -70,6 +70,11 @@ class BackgroundService {
return AppLocalizations.delegate.load(match);
}
static Future<void> openBatteryOptimizationSettings() async {
if (!PlatformInfo.isAndroid) return;
await FlutterForegroundTask.openIgnoreBatteryOptimizationSettings();
}
Future<void> stop() async {
if (!PlatformInfo.isAndroid) return;
final running = await FlutterForegroundTask.isRunningService;
+28 -2
View File
@@ -630,6 +630,9 @@ enum ImageReassemblyFailureReason {
/// Reassembled but the metadata byte was undecodable
/// ([ImageChunkStatus.unsupportedFormat]).
unsupportedFormat,
/// Dropped by [ImageReassembler.clear] (disconnect / new session).
disconnected,
}
/// A fully reassembled image.
@@ -852,10 +855,27 @@ class ImageReassembler {
/// Keys of the remembered completed images (test/debug aid).
Iterable<ImageStreamKey> get completedKeys => _recentlyCompleted.keys;
/// Drops everything (e.g. on disconnect). Does not fire [onFailed].
void clear() {
/// Drops everything (e.g. on disconnect). In-progress streams are reported
/// through [onFailed] right away, so their bubbles stop showing "receiving";
/// nothing is left behind for [evictExpired] to report later.
void clear({DateTime? now}) {
final at = now ?? _clock();
final dropped = _pending.values.toList();
_pending.clear();
_recentlyCompleted.clear();
for (final entry in dropped) {
onFailed?.call(
ImageReassemblyFailure(
key: entry.key,
total: entry.total,
receivedDataChunks: entry.bodies.length,
hadParity: entry.hasParity,
firstSeen: entry.firstSeen,
expiredAt: at,
reason: ImageReassemblyFailureReason.disconnected,
),
);
}
}
/// Feeds one received GRP_DATA blob.
@@ -883,6 +903,12 @@ class ImageReassembler {
// A parity chunk must carry at least its length byte.
return ImageChunkOutcome(ImageChunkStatus.malformed, header: header);
}
if (!header.isParity && body.length > kImageChunkBodyBytes) {
// The blob cap leaves room for one byte more than the XOR buffer holds;
// such a body can never come from [buildImageChunks] and would overrun
// parity recovery.
return ImageChunkOutcome(ImageChunkStatus.malformed, header: header);
}
final key = ImageStreamKey(
senderPrefix: header.senderPrefix,
+31 -2
View File
@@ -90,6 +90,10 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
String? _lastError;
Future<void> _queue = Future<void>.value();
ImageCodecSession? _session;
/// Teardown started by [handleMemoryPressure]; [_ensureSession] waits for it
/// so a second isolate is never spawned while the first is still resident.
Future<void>? _pendingRelease;
ImageCodecBundle? _loadedBundle;
ImageCodecBundle? _failedBundle;
int _downloadedBytes = 0;
@@ -980,6 +984,17 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
return bitstream;
}
@override
Future<Uint8List?> decodePreview(Uint8List payload) async {
if (!canDecode) return null;
final result = await decodeBitstream(
bitstream: payload,
ratePoint: aeicRatePointForUi(kImageSendRatePoint),
resolution: kImageCodecSquareSize,
);
return result?.pngBytes;
}
/// Encodes an already-decoded RGB image.
///
/// [rgbBytes] must be exactly `512 * 512 * 3` packed 8-bit RGB. Anything else
@@ -1339,6 +1354,12 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
// ---- model memory (mirrors translation_service.dart:586-629) -------------
Future<ImageCodecSession?> _ensureSession(ImageCodecBundle bundle) async {
final pendingRelease = _pendingRelease;
if (pendingRelease != null) {
try {
await pendingRelease;
} catch (_) {}
}
if (_session != null && _loadedBundle == bundle) {
return _session;
}
@@ -1455,8 +1476,16 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
if (session != null) {
// Ask for the big half back before the shutdown handshake, so the peak
// does not have to wait on isolate teardown.
await session.release(decoder: true);
await session.dispose();
final release = () async {
await session.release(decoder: true);
await session.dispose();
}();
_pendingRelease = release;
try {
await release;
} finally {
if (identical(_pendingRelease, release)) _pendingRelease = null;
}
}
appLogger.info('Image codec model evicted', tag: 'ImageCodec');
_notify();
+15 -1
View File
@@ -358,6 +358,19 @@ class MapTileCacheService extends ChangeNotifier {
String get urlTemplate => _buildUrlTemplate(appSettingsService.settings);
/// Cache key for a tile URL: the URL without its `api_key`, so rotating the
/// Stadia key does not orphan every offline tile.
static String tileCacheKey(String url) {
final uri = Uri.tryParse(url);
if (uri == null || !uri.queryParameters.containsKey('api_key')) return url;
final params = Map<String, String>.of(uri.queryParameters)
..remove('api_key');
final stripped = params.isEmpty
? uri.replace(query: '')
: uri.replace(queryParameters: params);
return stripped.toString().replaceFirst(RegExp(r'\?$'), '');
}
TileBuilder? get tileBuilder => null;
static bool shouldApplyDarkFilterForSettings(
@@ -614,7 +627,7 @@ class MapTileCacheService extends ChangeNotifier {
final pending = <Future<void>>[];
Future<void> queueDownload(String url) async {
final future = cacheManager
.downloadFile(url, key: url, authHeaders: authHeaders)
.downloadFile(url, key: tileCacheKey(url), authHeaders: authHeaders)
.then((_) {
completed += 1;
})
@@ -828,6 +841,7 @@ class CachedNetworkTileProvider extends TileProvider {
final url = getTileUrl(coordinates, options);
return CachedNetworkImageProvider(
url,
cacheKey: MapTileCacheService.tileCacheKey(url),
cacheManager: cacheManager,
headers: headers,
);
+55 -14
View File
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:uuid/uuid.dart';
import 'package:crypto/crypto.dart';
import '../connector/meshcore_protocol.dart';
import '../models/contact.dart';
import '../models/message.dart';
import '../models/path_selection.dart';
@@ -34,7 +35,7 @@ typedef AckHashMapping = ({
});
class RetryServiceConfig {
final void Function(Contact, String, int, int) sendMessage;
final FutureOr<void> Function(Contact, String, int, int) sendMessage;
final void Function(String, Message) addMessage;
final void Function(Message) updateMessage;
final Function(Contact)? clearContactPath;
@@ -209,21 +210,46 @@ class MessageRetryService extends ChangeNotifier {
final messageId = queue.removeAt(0);
if (_pendingMessages.containsKey(messageId)) {
_activeMessages.add(messageId);
_attemptSend(messageId).catchError((e) {
debugPrint('_attemptSend threw for $messageId: $e');
final msg = _pendingMessages[messageId];
if (msg != null) {
final failed = msg.copyWith(status: MessageStatus.failed);
_pendingMessages[messageId] = failed;
_config?.updateMessage(failed);
}
_onMessageResolved(messageId, contactKey);
});
_attemptSendOrFail(messageId);
return;
}
}
}
void _attemptSendOrFail(String messageId) {
_attemptSend(messageId).catchError((Object e) {
debugPrint('_attemptSend threw for $messageId: $e');
_config?.debugLogService?.warn(
'Send failed for message $messageId: $e',
tag: 'AckHash',
);
_failMessage(messageId);
});
}
/// Marks a message that could not be handed to the radio as failed and
/// releases its in-flight slot so the contact's queue keeps moving.
void _failMessage(String messageId) {
final message = _pendingMessages[messageId];
if (message == null) return;
_timeoutTimers[messageId]?.cancel();
if (message.status != MessageStatus.failed &&
message.status != MessageStatus.delivered) {
_config?.updateMessage(message.copyWith(status: MessageStatus.failed));
}
_cleanupMessage(messageId);
notifyListeners();
}
/// Fails every pending and queued message. Call when the radio link drops:
/// nothing in flight can be sent or acknowledged any more.
void failAllPending() {
_sendQueue.clear();
for (final messageId in _pendingMessages.keys.toList()) {
_failMessage(messageId);
}
}
void _onMessageResolved(String messageId, String contactKey) {
if (_resolvedMessages.contains(messageId)) return;
_resolvedMessages.add(messageId);
@@ -358,6 +384,9 @@ class MessageRetryService extends ChangeNotifier {
// Compute expected ACK hash that device will return in RESP_CODE_SENT
// IMPORTANT: Use the transformed text (with SMAZ encoding if enabled) to match device's hash
final selfPubKey = config.getSelfPublicKey?.call();
if (config.getSelfPublicKey != null && selfPubKey == null) {
throw StateError('Self public key unknown; cannot track ACK');
}
if (selfPubKey != null) {
final outboundText =
config.prepareContactOutboundText?.call(contact, message.text) ??
@@ -380,7 +409,7 @@ class MessageRetryService extends ChangeNotifier {
);
}
config.sendMessage(contact, message.text, attempt, timestampSeconds);
await config.sendMessage(contact, message.text, attempt, timestampSeconds);
}
bool updateMessageFromSent(int ackHash, int timeoutMs) {
@@ -535,7 +564,8 @@ class MessageRetryService extends ChangeNotifier {
tag: 'AckHash',
);
if (message.retryCount < maxRetries - 1) {
if (message.retryCount < maxRetries - 1 &&
_textFitsAttempt(message, contact, message.retryCount + 1)) {
final backoffMs = 1000 * (1 << message.retryCount);
if (selection != null) {
@@ -563,7 +593,7 @@ class MessageRetryService extends ChangeNotifier {
_timeoutTimers[messageId] = Timer(Duration(milliseconds: backoffMs), () {
if (_pendingMessages.containsKey(messageId)) {
_attemptSend(messageId);
_attemptSendOrFail(messageId);
}
});
} else {
@@ -598,6 +628,17 @@ class MessageRetryService extends ChangeNotifier {
}
}
/// From attempt 4 on the firmware appends [0][attempt] to the payload and
/// rejects text longer than MAX_TEXT_LEN - 2 (BaseChatMesh::composeMsgPacket).
bool _textFitsAttempt(Message message, Contact contact, int attempt) {
if (attempt <= maxFullLengthTextAttempt) return true;
final outboundText =
_config?.prepareContactOutboundText?.call(contact, message.text) ??
message.text;
return utf8.encode(outboundText).length <=
maxTextPayloadBytesAfterFullLengthAttempts;
}
void _moveAckHashesToHistory(String messageId) {
final ackHashes = _expectedAckHashes.remove(messageId);
if (ackHashes != null && ackHashes.isNotEmpty) {
+24 -8
View File
@@ -8,6 +8,7 @@ import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import '../helpers/message_url_image_helper.dart';
import '../helpers/reaction_helper.dart';
import '../l10n/app_localizations.dart';
import '../storage/prefs_manager.dart';
import '../utils/platform_info.dart';
class NotificationService {
@@ -123,9 +124,11 @@ class NotificationService {
// Cached "are we allowed to post notifications" result. Null = not yet
// determined. Avoids calling _notifications.show() when it would only throw
// "You must request notifications permissions first" (every web build, and
// Android 13+ before the user grants the permission).
// "You must request notifications permissions first" (every web build).
// Android denials are never cached so a later grant in system settings is
// picked up without restarting the app.
bool? _canNotify;
static const _permissionRequestedKey = 'notification_permission_requested';
Future<bool> _ensureCanNotify() async {
if (!await _ensureInitialized()) return false;
@@ -143,8 +146,9 @@ class NotificationService {
AndroidFlutterLocalNotificationsPlugin
>();
if (androidPlugin != null) {
final enabled = await androidPlugin.areNotificationsEnabled();
return _canNotify = enabled ?? false;
final enabled = await androidPlugin.areNotificationsEnabled() ?? false;
if (enabled) _canNotify = true;
return enabled;
}
// iOS/macOS request permission during initialize(); desktop has no gate.
@@ -163,8 +167,8 @@ class NotificationService {
>();
if (androidPlugin != null) {
final granted = await androidPlugin.requestNotificationsPermission();
_canNotify = granted ?? false;
return _canNotify!;
if (granted == true) _canNotify = true;
return granted ?? false;
}
// iOS permissions are requested during initialization
@@ -178,13 +182,25 @@ class NotificationService {
badge: true,
sound: true,
);
_canNotify = granted ?? false;
return _canNotify!;
if (granted == true) _canNotify = true;
return granted ?? false;
}
return true;
}
/// Asks for the Android 13+ notification permission the first time it is
/// needed. Never re-prompts after the user has answered once; iOS/macOS
/// already prompt during [initialize].
Future<void> requestPermissionsOnce() async {
if (!PlatformInfo.isAndroid || !await _ensureInitialized()) return;
final prefs = PrefsManager.instance;
if (prefs.getBool(_permissionRequestedKey) ?? false) return;
if (await _ensureCanNotify()) return;
await prefs.setBool(_permissionRequestedKey, true);
await requestPermissions();
}
/// Format special message types for human-readable notifications.
static String formatNotificationText(String text) {
final trimmed = text.trim();
+94 -96
View File
@@ -9,8 +9,7 @@ class PathHistoryService extends ChangeNotifier {
final Map<String, ContactPathHistory> _cache = {};
final Map<String, int> _autoRotationIndex = {};
final Map<String, _FloodStats> _floodStats = {};
final Set<String> _pendingLoads = {};
final Map<String, List<_DeferredPathRecord>> _deferredRecords = {};
final Map<String, Future<void>> _pendingLoads = {};
// LRU cache eviction tracking
static const int _maxCachedContacts = 50;
@@ -23,6 +22,16 @@ class PathHistoryService extends ChangeNotifier {
PathHistoryService(this._storage);
void setDevicePublicKey(String publicKeyHex) {
_storage.setPublicKeyHex = publicKeyHex;
_cache.clear();
_cacheAccessOrder.clear();
_autoRotationIndex.clear();
_floodStats.clear();
_version++;
notifyListeners();
}
Future<void> initialize() async {
// Load cached path histories on startup if needed
}
@@ -40,7 +49,7 @@ class PathHistoryService extends ChangeNotifier {
pathBytes: contact.path,
successCount: 0,
failureCount: 0,
routeWeight: initialWeight,
initialWeight: initialWeight,
timestamp: null,
);
}
@@ -74,6 +83,20 @@ class PathHistoryService extends ChangeNotifier {
double maxWeight = 5.0,
}) {
if (pathBytes.isEmpty || hopCount < 0) return;
if (!_cache.containsKey(contactPubKeyHex)) {
_ensureLoaded(contactPubKeyHex).then((_) {
if (!_cache.containsKey(contactPubKeyHex)) return;
recordFloodPathAttribution(
contactPubKeyHex: contactPubKeyHex,
pathBytes: pathBytes,
hopCount: hopCount,
tripTimeMs: tripTimeMs,
successIncrement: successIncrement,
maxWeight: maxWeight,
);
});
return;
}
final existing = _findPathRecord(contactPubKeyHex, pathBytes);
final successCount = (existing?.successCount ?? 0) + 1;
@@ -124,6 +147,22 @@ class PathHistoryService extends ChangeNotifier {
return;
}
if (!_cache.containsKey(contactPubKeyHex)) {
_ensureLoaded(contactPubKeyHex).then((_) {
if (!_cache.containsKey(contactPubKeyHex)) return;
recordPathResult(
contactPubKeyHex,
selection,
success: success,
tripTimeMs: tripTimeMs,
successIncrement: successIncrement,
failureDecrement: failureDecrement,
maxWeight: maxWeight,
);
});
return;
}
final existing = _findPathRecord(contactPubKeyHex, selection.pathBytes);
final successCount = (existing?.successCount ?? 0) + (success ? 1 : 0);
final failureCount = (existing?.failureCount ?? 0) + (success ? 0 : 1);
@@ -222,73 +261,11 @@ class PathHistoryService extends ChangeNotifier {
required List<int> pathBytes,
required int successCount,
required int failureCount,
double routeWeight = 1.0,
double? routeWeight,
double initialWeight = 1.0,
DateTime? timestamp,
}) {
var history = _cache[contactPubKeyHex];
if (history == null) {
// If a load is already in progress, defer this record
if (_pendingLoads.contains(contactPubKeyHex)) {
_deferredRecords.putIfAbsent(contactPubKeyHex, () => []);
_deferredRecords[contactPubKeyHex]!.add(
_DeferredPathRecord(
hopCount: hopCount,
tripTimeMs: tripTimeMs,
wasFloodDiscovery: wasFloodDiscovery,
pathBytes: pathBytes,
successCount: successCount,
failureCount: failureCount,
routeWeight: routeWeight,
timestamp: timestamp,
),
);
return;
}
_pendingLoads.add(contactPubKeyHex);
_loadHistoryFromStorage(contactPubKeyHex).then((loaded) {
_cache[contactPubKeyHex] =
loaded ??
ContactPathHistory(
contactPubKeyHex: contactPubKeyHex,
recentPaths: [],
);
_addPathRecordInternal(
contactPubKeyHex,
hopCount,
tripTimeMs,
wasFloodDiscovery,
pathBytes,
successCount,
failureCount,
routeWeight,
timestamp,
);
// Apply any deferred records
final deferred = _deferredRecords.remove(contactPubKeyHex);
if (deferred != null) {
for (final record in deferred) {
_addPathRecordInternal(
contactPubKeyHex,
record.hopCount,
record.tripTimeMs,
record.wasFloodDiscovery,
record.pathBytes,
record.successCount,
record.failureCount,
record.routeWeight,
record.timestamp,
);
}
}
_pendingLoads.remove(contactPubKeyHex);
});
return;
}
_addPathRecordInternal(
void add() => _addPathRecordInternal(
contactPubKeyHex,
hopCount,
tripTimeMs,
@@ -297,8 +274,34 @@ class PathHistoryService extends ChangeNotifier {
successCount,
failureCount,
routeWeight,
initialWeight,
timestamp,
);
if (_cache.containsKey(contactPubKeyHex)) {
add();
} else {
_ensureLoaded(contactPubKeyHex).then((_) => add());
}
}
Future<void> _ensureLoaded(String contactPubKeyHex) {
if (_cache.containsKey(contactPubKeyHex)) return Future.value();
return _pendingLoads[contactPubKeyHex] ??=
_loadHistoryFromStorage(contactPubKeyHex)
.then((loaded) {
_cache[contactPubKeyHex] ??=
loaded ??
ContactPathHistory(
contactPubKeyHex: contactPubKeyHex,
recentPaths: [],
);
_trackAccess(contactPubKeyHex);
_evictIfNeeded();
})
.whenComplete(() {
_pendingLoads.remove(contactPubKeyHex);
});
}
void _addPathRecordInternal(
@@ -309,7 +312,8 @@ class PathHistoryService extends ChangeNotifier {
List<int> pathBytes,
int successCount,
int failureCount,
double routeWeight,
double? routeWeight,
double initialWeight,
DateTime? timestamp,
) {
var history = _cache[contactPubKeyHex];
@@ -326,6 +330,7 @@ class PathHistoryService extends ChangeNotifier {
wasFloodDiscovery = existing.wasFloodDiscovery || wasFloodDiscovery;
timestamp ??= existing.timestamp;
}
routeWeight ??= existing?.routeWeight ?? initialWeight;
final newRecord = PathRecord(
hopCount: hopCount,
@@ -361,6 +366,24 @@ class PathHistoryService extends ChangeNotifier {
notifyListeners();
}
/// Whether this contact's history is in the in-memory cache.
bool isCached(String contactPubKeyHex) =>
_cache.containsKey(contactPubKeyHex);
/// Paths already in memory, without loading from storage or changing the
/// cache order. For bulk readers that must not churn the 50-contact cache.
List<PathRecord> peekRecentPaths(String contactPubKeyHex) =>
_cache[contactPubKeyHex]?.recentPaths ?? const [];
/// Reads saved paths straight from storage without adding them to the
/// cache, evicting anything, or notifying listeners.
Future<List<PathRecord>> readStoredPaths(String contactPubKeyHex) async {
final cached = _cache[contactPubKeyHex];
if (cached != null) return cached.recentPaths;
final stored = await _loadHistoryFromStorage(contactPubKeyHex);
return stored?.recentPaths ?? const [];
}
List<PathRecord> getRecentPaths(String contactPubKeyHex) {
final history = _cache[contactPubKeyHex];
if (history != null) {
@@ -368,11 +391,8 @@ class PathHistoryService extends ChangeNotifier {
return history.recentPaths;
}
_loadHistoryFromStorage(contactPubKeyHex).then((loaded) {
if (loaded != null) {
_cache[contactPubKeyHex] = loaded;
_trackAccess(contactPubKeyHex);
_evictIfNeeded();
_ensureLoaded(contactPubKeyHex).then((_) {
if (_cache[contactPubKeyHex]?.recentPaths.isNotEmpty ?? false) {
_version++;
notifyListeners();
}
@@ -579,28 +599,6 @@ class PathHistoryService extends ChangeNotifier {
}
}
class _DeferredPathRecord {
final int hopCount;
final int tripTimeMs;
final bool wasFloodDiscovery;
final List<int> pathBytes;
final int successCount;
final int failureCount;
final double routeWeight;
final DateTime? timestamp;
_DeferredPathRecord({
required this.hopCount,
required this.tripTimeMs,
required this.wasFloodDiscovery,
required this.pathBytes,
required this.successCount,
required this.failureCount,
this.routeWeight = 1.0,
this.timestamp,
});
}
class _FloodStats {
int successCount = 0;
int failureCount = 0;
+22 -5
View File
@@ -66,6 +66,10 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
String? _dirPath;
Future<String>? _pending;
/// Last queued sidecar operation per id. Writes share one `.tmp` path, so
/// two in flight for the same id would interleave; each waits for the last.
final Map<String, Future<void>> _sidecarOps = <String, Future<void>>{};
FileReceivedImageBlobStore({
Future<Directory> Function()? baseDirectory,
this.directoryName = 'received_images',
@@ -190,7 +194,19 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
/// atomic within a directory on every platform we ship, so a reader either
/// sees the old record or the new one.
@override
Future<void> writeSidecar(String streamId, String json) async {
Future<void> writeSidecar(String streamId, String json) =>
_serializeSidecar(streamId, () => _writeSidecarNow(streamId, json));
Future<void> _serializeSidecar(String streamId, Future<void> Function() op) {
final previous = _sidecarOps[streamId] ?? Future<void>.value();
final next = previous.then((_) => op());
_sidecarOps[streamId] = next;
return next.whenComplete(() {
if (identical(_sidecarOps[streamId], next)) _sidecarOps.remove(streamId);
});
}
Future<void> _writeSidecarNow(String streamId, String json) async {
try {
final finalPath = await _pathFor(streamId, _sidecarExt);
final tmpPath = await _pathFor(streamId, _tmpExt);
@@ -207,10 +223,11 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
}
@override
Future<void> deleteSidecar(String streamId) async {
await _delete(streamId, _sidecarExt);
await _delete(streamId, _tmpExt);
}
Future<void> deleteSidecar(String streamId) =>
_serializeSidecar(streamId, () async {
await _delete(streamId, _sidecarExt);
await _delete(streamId, _tmpExt);
});
/// Startup scan. Also the only place orphaned bytes are reaped: anything
/// whose sidecar is gone is invisible to the store and therefore to the
+61 -7
View File
@@ -595,6 +595,10 @@ class ReceivedImageStore extends ChangeNotifier {
/// True when the queue stopped because the codec was busy encoding. Cleared
/// by anything that could plausibly have freed it.
bool _parkedOnBusyDecoder = false;
/// Set by [handleMemoryPressure] so the decode it cancels is parked rather
/// than reported as corrupt.
bool _cancelRequested = false;
bool _foreground = true;
bool _disposed = false;
@@ -775,10 +779,13 @@ class ReceivedImageStore extends ChangeNotifier {
// `conflicting` means the reassembler threw the old stream away and
// restarted from this chunk. A stream that had already been surfaced
// keeps its id (and therefore its message) only if it was still
// receiving; anything else gets a fresh entry.
// receiving; anything else gets a fresh entry. The same goes for a
// plain `accepted`: once an entry is past `receiving` the reassembler
// reports its stragglers as `duplicate`, so an accepted chunk on that
// key is a new image reusing the 8-bit id and must not overwrite it.
final resets = outcome.status == ImageChunkStatus.conflicting;
if (existing != null &&
(!resets || existing.state == ReceivedImageState.receiving)) {
existing.state == ReceivedImageState.receiving) {
final updated = existing.copyWith(
state: ReceivedImageState.receiving,
receivedChunks: resets
@@ -824,7 +831,9 @@ class ReceivedImageStore extends ChangeNotifier {
channelIndex: channelIndex,
),
);
if (entry == null) return null;
if (entry == null || entry.state != ReceivedImageState.receiving) {
return null;
}
_queue.remove(entry.streamId);
return _store(
entry.copyWith(
@@ -847,7 +856,9 @@ class ReceivedImageStore extends ChangeNotifier {
) async {
final key = result.key;
var entry = entryForKey(key);
if (entry == null) {
// A one-chunk image completes without an `accepted` first, so the key may
// still point at an older, finished image that reused the id.
if (entry == null || entry.state != ReceivedImageState.receiving) {
final streamId = _uniqueStreamId(
senderPrefix: key.senderPrefix,
imgId: key.imgId,
@@ -906,7 +917,7 @@ class ReceivedImageStore extends ChangeNotifier {
// Already completed by a later chunk; the failure is stale.
return entry;
}
return _store(
final failed = await _store(
entry.copyWith(
// `isCorrupt` means every chunk arrived but the bytes were unusable
// (CRC-16 mismatch or an undecodable metadata byte). The UI must say
@@ -919,6 +930,8 @@ class ReceivedImageStore extends ChangeNotifier {
error: failure.isCorrupt ? failure.reason.name : null,
),
);
await evictToBudget(protect: failed.streamId);
return failed;
}
/// Records the local user's own send so the outgoing bubble can show the real
@@ -1027,6 +1040,7 @@ class ReceivedImageStore extends ChangeNotifier {
/// Cancels the running decode and stops the queue; the entry goes back to
/// `reassembled` and will be picked up again later.
Future<void> handleMemoryPressure() async {
_cancelRequested = true;
decoder?.cancelCodecJob();
_queue.clear();
for (final entry in _entries.values.toList()) {
@@ -1190,6 +1204,7 @@ class ReceivedImageStore extends ChangeNotifier {
return;
}
final started = _clock();
_cancelRequested = false;
await _store(entry.copyWith(state: ReceivedImageState.decoding));
ImageCodecResult? result;
@@ -1201,7 +1216,14 @@ class ReceivedImageStore extends ChangeNotifier {
);
} catch (error) {
final current = _entries[entry.streamId] ?? entry;
if (!_foreground) {
if (_cancelRequested) {
await _store(
current.copyWith(
state: ReceivedImageState.reassembled,
needsManualDecode: true,
),
);
} else if (!_foreground) {
await _store(current.copyWith(state: ReceivedImageState.reassembled));
} else {
await _store(
@@ -1224,6 +1246,16 @@ class ReceivedImageStore extends ChangeNotifier {
}
final png = result.pngBytes;
if (result.status != ImageCodecStatus.completed || png == null) {
if (_cancelRequested) {
// The codec reports a killed job as `failed`; the bitstream is fine.
await _store(
current.copyWith(
state: ReceivedImageState.reassembled,
needsManualDecode: true,
),
);
return;
}
await _store(
current.copyWith(
state: ReceivedImageState.failedCorrupt,
@@ -1348,9 +1380,15 @@ class ReceivedImageStore extends ChangeNotifier {
final evicted = <String>[];
final now = _clock();
// 1. Age budget: nothing survives, not even the bitstream.
// 1. Age budget: nothing survives, not even the bitstream. A failed image
// has no bubble worth keeping, so it goes entirely, sidecar included.
for (final entry in _entries.values.toList()) {
if (now.difference(entry.firstSeen) <= maxAge) continue;
if (entry.state.isFailure) {
await deleteImage(entry.streamId);
evicted.add(entry.streamId);
continue;
}
if (!entry.pngStored && !entry.bitstreamStored) continue;
await blobs.deletePng(entry.streamId);
await blobs.deleteBitstream(entry.streamId);
@@ -1414,6 +1452,22 @@ class ReceivedImageStore extends ChangeNotifier {
evicted.add(victim.streamId);
}
// 3. Failed entries hold no PNG, so the loop above never counts them; cap
// them by entry count, oldest first, or a noisy mesh grows the sidecars
// (and the startup load) without bound.
if (_entries.length > maxImages) {
final failures =
_entries.values
.where((e) => e.state.isFailure && e.streamId != protect)
.toList()
..sort((a, b) => a.firstSeen.compareTo(b.firstSeen));
for (final victim in failures) {
if (_entries.length <= maxImages) break;
await deleteImage(victim.streamId);
evicted.add(victim.streamId);
}
}
if (evicted.isNotEmpty) _notify();
return evicted;
}
+33 -5
View File
@@ -4,6 +4,16 @@ import '../models/path_selection.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
/// Companion firmware (MeshCore commit 4a869163, 2025-12-30) replaces the CLI
/// frame timestamp with the companion node's RTC for TXT_TYPE_CLI_DATA, so a
/// plain "clock sync" sets the repeater clock to the node clock. The official
/// meshcore-cli translates it to an explicit `time <epoch>` command instead;
/// do the same so the repeater always gets the phone's time.
String normalizeRepeaterClockSyncCommand(String command, {int? nowSeconds}) {
final epoch = nowSeconds ?? DateTime.now().millisecondsSinceEpoch ~/ 1000;
return command.trim().toLowerCase() == 'clock sync' ? 'time $epoch' : command;
}
class RepeaterCommandService {
final MeshCoreConnector _connector;
final Map<String, Completer<String>> _pendingCommands = {};
@@ -13,18 +23,22 @@ class RepeaterCommandService {
int _prefixCounter = 0;
static const int maxRetries = 5;
static final RegExp _prefixPattern = RegExp(r'^[0-9A-Fa-f]{2}\|');
RepeaterCommandService(this._connector);
/// Send a CLI command to a repeater with automatic retries
/// Returns a future that completes when a response is received or after max retries
/// Returns a future that completes when a response is received or after max retries.
/// With [raw], the command is sent verbatim without the `XX|` reply prefix.
Future<String> sendCommand(
Contact repeater,
String command, {
Function(String)? onResponse,
Function(int)? onAttempt,
int retries = maxRetries,
bool raw = false,
}) async {
if (!raw) command = normalizeRepeaterClockSyncCommand(command);
final attemptCount = retries < 1 ? 1 : retries;
final selection = await _connector.preparePathForContactSend(repeater);
@@ -36,6 +50,7 @@ class RepeaterCommandService {
command,
selection,
attempt,
raw,
);
onResponse?.call(response);
return response;
@@ -52,6 +67,7 @@ class RepeaterCommandService {
String command,
PathSelection selection,
int attempt,
bool raw,
) async {
final repeaterKey = repeater.publicKeyHex;
final prefix = _nextPrefixToken();
@@ -62,7 +78,7 @@ class RepeaterCommandService {
_pendingByPrefix[prefix] = commandId;
try {
final framedCommand = '$prefix$command';
final framedCommand = raw ? command : '$prefix$command';
final pathLengthValue = selection.useFlood ? -1 : selection.hopCount;
final timestampSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000;
_connector.trackRepeaterAck(
@@ -112,6 +128,15 @@ class RepeaterCommandService {
}
}
/// Send [line] verbatim and don't wait for a reply. While `region load` is
/// active the firmware consumes each line before prefix stripping and
/// sends nothing back (simple_repeater/MyMesh.cpp handleCommand).
Future<void> sendUnansweredLine(Contact repeater, String line) {
return _connector.sendFrame(
buildSendCliCommandFrame(repeater.publicKey, line),
);
}
/// Call this when a text message response is received from a repeater
void handleResponse(Contact repeater, String responseText) {
// Find pending command for this repeater and complete it
@@ -119,14 +144,17 @@ class RepeaterCommandService {
String? commandId;
String responsePayload = responseText;
if (responseText.length >= 3 && responseText[2] == '|') {
final prefix = responseText.substring(0, 3);
if (_prefixPattern.hasMatch(responseText)) {
final prefix = responseText.substring(0, 3).toUpperCase();
commandId = _pendingByPrefix[prefix];
if (commandId == null || !commandId.startsWith('${repeaterKey}_')) {
return;
}
responsePayload = responseText.substring(3).trimLeft();
}
commandId ??= _pendingCommands.keys.firstWhere(
(id) => id.startsWith(repeaterKey),
(id) => id.startsWith('${repeaterKey}_'),
orElse: () => '',
);
+31 -9
View File
@@ -2,6 +2,7 @@ import 'dart:convert';
import '../models/delivery_observation.dart';
import '../models/path_history.dart';
import '../storage/prefs_manager.dart';
import '../utils/app_logger.dart';
class StorageService {
static const String _pathHistoryPrefix = 'path_history_';
@@ -11,6 +12,14 @@ class StorageService {
'repeater_auto_clock_sync_after_login';
static const String _deliveryObservationsKey = 'delivery_observations';
String _publicKeyHex = '';
set setPublicKeyHex(String value) =>
_publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
String _pathHistoryKey(String contactPubKeyHex) => _publicKeyHex.isEmpty
? '$_pathHistoryPrefix$contactPubKeyHex'
: '$_pathHistoryPrefix${_publicKeyHex}_$contactPubKeyHex';
Future<Map<String, bool>> _loadRepeaterAutoClockSyncAfterLogin() async {
final prefs = PrefsManager.instance;
final jsonStr = prefs.getString(_repeaterAutoClockSyncAfterLoginKey);
@@ -48,15 +57,18 @@ class StorageService {
ContactPathHistory history,
) async {
final prefs = PrefsManager.instance;
final key = '$_pathHistoryPrefix$contactPubKeyHex';
final key = _pathHistoryKey(contactPubKeyHex);
final jsonStr = jsonEncode(history.toJson());
await prefs.setString(key, jsonStr);
}
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) async {
final prefs = PrefsManager.instance;
final key = '$_pathHistoryPrefix$contactPubKeyHex';
final jsonStr = prefs.getString(key);
final key = _pathHistoryKey(contactPubKeyHex);
// Fall back to the pre-scoping key so learned routes survive the upgrade.
final jsonStr =
prefs.getString(key) ??
prefs.getString('$_pathHistoryPrefix$contactPubKeyHex');
if (jsonStr == null) return null;
@@ -70,8 +82,8 @@ class StorageService {
Future<void> clearPathHistory(String contactPubKeyHex) async {
final prefs = PrefsManager.instance;
final key = '$_pathHistoryPrefix$contactPubKeyHex';
await prefs.remove(key);
await prefs.remove(_pathHistoryKey(contactPubKeyHex));
await prefs.remove('$_pathHistoryPrefix$contactPubKeyHex');
}
Future<void> clearAllPathHistories() async {
@@ -173,14 +185,24 @@ class StorageService {
if (jsonStr == null) return [];
final List<dynamic> list;
try {
final list = jsonDecode(jsonStr) as List;
return list
.map((e) => DeliveryObservation.fromJson(e as Map<String, dynamic>))
.toList();
list = jsonDecode(jsonStr) as List<dynamic>;
} catch (e) {
appLogger.warn('Stored delivery observations are unreadable: $e');
return [];
}
final observations = <DeliveryObservation>[];
for (final e in list) {
try {
observations.add(
DeliveryObservation.fromJson(e as Map<String, dynamic>),
);
} catch (err) {
appLogger.warn('Skipping malformed delivery observation: $err');
}
}
return observations;
}
Future<void> clearDeliveryObservations() async {
+15 -6
View File
@@ -58,7 +58,10 @@ class TranslationFileStore {
required Stream<List<int>> chunks,
}) async {
final directoryPath = await modelDirectoryPath();
final file = File('$directoryPath/$fileName');
final finalPath = '$directoryPath/$fileName';
// Hidden until complete, so a killed download is swept by
// [scanDownloadedModels] instead of being registered as a model.
final file = File(_partPath(directoryPath, fileName));
final sink = file.openWrite();
var fileSizeBytes = 0;
var completed = false;
@@ -74,8 +77,9 @@ class TranslationFileStore {
await file.delete();
}
}
await file.rename(finalPath);
return DownloadedModelFile(
localPath: file.path,
localPath: finalPath,
fileSizeBytes: fileSizeBytes,
);
}
@@ -91,7 +95,8 @@ class TranslationFileStore {
}) async {
final dir = await modelDirectoryPath();
final finalPath = '$dir/$fileName';
final sink = File(finalPath).openWrite();
final partPath = _partPath(dir, fileName);
final sink = File(partPath).openWrite();
var totalSize = 0;
var completed = false;
try {
@@ -110,14 +115,18 @@ class TranslationFileStore {
}
}
if (!completed) {
final finalFile = File(finalPath);
if (finalFile.existsSync()) {
await finalFile.delete();
final partFile = File(partPath);
if (partFile.existsSync()) {
await partFile.delete();
}
}
}
await File(partPath).rename(finalPath);
return DownloadedModelFile(localPath: finalPath, fileSizeBytes: totalSize);
}
String _partPath(String dir, String fileName) =>
fileName.startsWith('.') ? '$dir/$fileName.part' : '$dir/.$fileName.part';
}
class DownloadedModelFile {
+18 -2
View File
@@ -271,10 +271,19 @@ class TranslationService extends ChangeNotifier {
_downloadTotalBytes ??= response.contentLength;
_notify();
final trackedStream = _trackDownloadProgress(response.stream);
return await _fileStore.writeModelBytes(
final downloaded = await _fileStore.writeModelBytes(
fileName: fileName,
chunks: trackedStream,
);
final expected = response.contentLength;
if (expected != null && downloaded.fileSizeBytes != expected) {
await _fileStore.deleteFile(downloaded.localPath);
throw StateError(
'Model download incomplete: '
'${downloaded.fileSizeBytes} of $expected bytes',
);
}
return downloaded;
} finally {
client.close();
}
@@ -350,10 +359,17 @@ class TranslationService extends ChangeNotifier {
);
}
final trackedStream = _trackDownloadProgress(response.stream);
await _fileStore.writeModelBytes(
final downloaded = await _fileStore.writeModelBytes(
fileName: chunkPath.split(RegExp(r'[/\\]')).last,
chunks: trackedStream,
);
final expected = end - start + 1;
if (downloaded.fileSizeBytes != expected) {
throw StateError(
'Range download incomplete: '
'${downloaded.fileSizeBytes} of $expected bytes',
);
}
}
void cancelDownload() {
+7 -1
View File
@@ -558,7 +558,9 @@ class UsbSerialService {
return;
}
if (data is ByteData) {
_ingestRawBytes(data.buffer.asUint8List());
_ingestRawBytes(
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes),
);
return;
}
_addFrameError(
@@ -571,7 +573,11 @@ class UsbSerialService {
}
void _handleSerialDone() {
final wasConnected = _status == UsbSerialStatus.connected;
unawaited(disconnect());
if (wasConnected) {
_addFrameError(StateError('USB serial connection closed'));
}
}
void _ingestRawBytes(Uint8List bytes) {