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:
1 parent
a64a33d0c0
commit
25f197c979
120 files changed
+10424
-687
No files matched your search
@@ -113,6 +113,10 @@ class AppSettingsService extends ChangeNotifier {
|
||||
await updateSettings(_settings.copyWith(enableMessageTracing: value));
|
||||
}
|
||||
|
||||
Future<void> setRegionOnHopsLine(bool value) async {
|
||||
await updateSettings(_settings.copyWith(regionOnHopsLine: value));
|
||||
}
|
||||
|
||||
Future<void> setMapCacheBounds(Map<String, double>? value) async {
|
||||
await updateSettings(_settings.copyWith(mapCacheBounds: value));
|
||||
}
|
||||
@@ -222,6 +226,12 @@ class AppSettingsService extends ChangeNotifier {
|
||||
await updateSettings(_settings.copyWith(channelMinHopsRetries: value));
|
||||
}
|
||||
|
||||
Future<void> setChannelMinHopsCountRepeaters(bool value) async {
|
||||
await updateSettings(
|
||||
_settings.copyWith(channelMinHopsCountRepeaters: value),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> setThemeMode(String value) async {
|
||||
await updateSettings(_settings.copyWith(themeMode: value));
|
||||
}
|
||||
|
||||
@@ -1117,10 +1117,15 @@ class ImageReassembler {
|
||||
|
||||
_FinishOutcome? _assemble(_PendingImage entry, {required bool recovered}) {
|
||||
final first = entry.bodies[0];
|
||||
// Chunk 0 must hold the metadata byte; anything shorter cannot
|
||||
// be a chunk 0 from this framing, so keep waiting rather than guessing.
|
||||
if (first == null || first.length < kImageChunkZeroMetadataBytes) {
|
||||
return null;
|
||||
if (first == null) return null;
|
||||
// Chunk 0 must hold the metadata byte; anything shorter cannot be a chunk
|
||||
// 0 from this framing. Every chunk is already here, so waiting would only
|
||||
// leave the stream on "receiving" until the TTL reports it as incomplete.
|
||||
if (first.length < kImageChunkZeroMetadataBytes) {
|
||||
return const _FinishOutcome.failed(
|
||||
ImageChunkStatus.unsupportedFormat,
|
||||
ImageReassemblyFailureReason.unsupportedFormat,
|
||||
);
|
||||
}
|
||||
final metadata = ImageStreamMetadata.decode(first[0]);
|
||||
final out = BytesBuilder();
|
||||
|
||||
@@ -487,6 +487,9 @@ class OnnxImageCodecBackend implements ImageCodecBackend {
|
||||
bool Function()? shouldCancel,
|
||||
}) async {
|
||||
_checkRatePoint(ratePoint);
|
||||
// A previous decode leaves the 2.16 GiB synthesis session resident; the
|
||||
// entropy graph must never be created on top of it.
|
||||
await releaseDecoderSession();
|
||||
final codec = await _ensureEntropy(resolution, forDecode: false);
|
||||
try {
|
||||
// The entropy session stays up on purpose: a second photo is free.
|
||||
@@ -509,6 +512,9 @@ class OnnxImageCodecBackend implements ImageCodecBackend {
|
||||
bool Function()? shouldCancel,
|
||||
}) async {
|
||||
_checkRatePoint(ratePoint);
|
||||
// Same rule in the other direction: the previous decode's synthesis
|
||||
// session is still up, and the entropy graph is about to load.
|
||||
await releaseDecoderSession();
|
||||
final codec = await _ensureEntropy(resolution, forDecode: true);
|
||||
final Float32List yHat;
|
||||
try {
|
||||
|
||||
@@ -99,7 +99,11 @@ class ImageCodecFileStore {
|
||||
}) async {
|
||||
final directoryPath = await modelDirectoryPath();
|
||||
final file = File('$directoryPath/$fileName');
|
||||
final sink = file.openWrite();
|
||||
// Written under a hidden temp name and renamed into place, so a kill
|
||||
// mid-write never leaves a truncated file under the real name, which the
|
||||
// startup scan would register as an installed model.
|
||||
final temp = File(_tempPathFor(directoryPath, fileName));
|
||||
final sink = temp.openWrite();
|
||||
var fileSizeBytes = 0;
|
||||
var completed = false;
|
||||
try {
|
||||
@@ -110,16 +114,22 @@ class ImageCodecFileStore {
|
||||
completed = true;
|
||||
} finally {
|
||||
await sink.close();
|
||||
if (!completed && file.existsSync()) {
|
||||
await file.delete();
|
||||
if (!completed && temp.existsSync()) {
|
||||
await temp.delete();
|
||||
}
|
||||
}
|
||||
await temp.rename(file.path);
|
||||
return DownloadedCodecFile(
|
||||
localPath: file.path,
|
||||
fileSizeBytes: fileSizeBytes,
|
||||
);
|
||||
}
|
||||
|
||||
/// Hidden (leading dot), so [scanDownloadedModels] never lists it and sweeps
|
||||
/// it as junk if a kill leaves it behind.
|
||||
static String _tempPathFor(String directoryPath, String fileName) =>
|
||||
'$directoryPath/.$fileName.part';
|
||||
|
||||
Future<String> chunkFilePath(String fileName, int index) async {
|
||||
final dir = await modelDirectoryPath();
|
||||
return '$dir/.${fileName}_chunk_$index';
|
||||
@@ -195,7 +205,11 @@ class ImageCodecFileStore {
|
||||
}) async {
|
||||
final dir = await modelDirectoryPath();
|
||||
final finalPath = '$dir/$fileName';
|
||||
final sink = File(finalPath).openWrite();
|
||||
// Merged into a hidden temp file first, for the same reason as
|
||||
// [writeModelBytes]: a kill mid-merge must not leave a truncated file
|
||||
// under the real name.
|
||||
final tempPath = _tempPathFor(dir, fileName);
|
||||
final sink = File(tempPath).openWrite();
|
||||
var totalSize = 0;
|
||||
var completed = false;
|
||||
try {
|
||||
@@ -208,6 +222,7 @@ class ImageCodecFileStore {
|
||||
} finally {
|
||||
await sink.close();
|
||||
if (completed) {
|
||||
await File(tempPath).rename(finalPath);
|
||||
for (final chunkPath in chunkPaths) {
|
||||
final file = File(chunkPath);
|
||||
if (file.existsSync()) {
|
||||
@@ -219,9 +234,9 @@ class ImageCodecFileStore {
|
||||
// merge target is thrown away. (The previous version deleted the chunks
|
||||
// unconditionally, which is why an interrupted 872 MB download restarted
|
||||
// from zero.)
|
||||
final finalFile = File(finalPath);
|
||||
if (finalFile.existsSync()) {
|
||||
await finalFile.delete();
|
||||
final tempFile = File(tempPath);
|
||||
if (tempFile.existsSync()) {
|
||||
await tempFile.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -413,17 +413,26 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
for (final asset in spec.assets) asset.fileName,
|
||||
};
|
||||
|
||||
// A file only counts when its size matches the registry: one cut short by
|
||||
// a kill mid-write must not register the bundle as installed, or every
|
||||
// decode fails and reads as "corrupt". Only enforced where a digest pins
|
||||
// the file, since the size is otherwise advisory.
|
||||
bool intact(ImageCodecModelAsset asset) {
|
||||
final file = onDisk[asset.fileName];
|
||||
if (file == null) return false;
|
||||
if (!asset.hasChecksum || asset.sizeBytes <= 0) return true;
|
||||
return file.fileSizeBytes == asset.sizeBytes;
|
||||
}
|
||||
|
||||
for (final spec in imageCodecPresetModels) {
|
||||
final graphFile = onDisk[spec.fileName];
|
||||
if (graphFile == null) continue;
|
||||
final present = [
|
||||
for (final asset in spec.assets)
|
||||
if (onDisk.containsKey(asset.fileName)) asset.fileName,
|
||||
if (intact(asset)) asset.fileName,
|
||||
];
|
||||
final existing = existingByPath[graphFile.localPath];
|
||||
final complete = spec.assets.every(
|
||||
(asset) => onDisk.containsKey(asset.fileName),
|
||||
);
|
||||
final complete = spec.assets.every(intact);
|
||||
merged.add(
|
||||
ImageCodecModelRecord(
|
||||
id: spec.id,
|
||||
@@ -437,8 +446,7 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
assetFileNames: present,
|
||||
assetRoles: {
|
||||
for (final asset in spec.assets)
|
||||
if (onDisk.containsKey(asset.fileName))
|
||||
asset.fileName: asset.role,
|
||||
if (intact(asset)) asset.fileName: asset.role,
|
||||
},
|
||||
bundleVersion: complete ? kImageCodecBundleVersion : 0,
|
||||
),
|
||||
@@ -1360,8 +1368,14 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
await pendingRelease;
|
||||
} catch (_) {}
|
||||
}
|
||||
if (_session != null && _loadedBundle == bundle) {
|
||||
return _session;
|
||||
final cached = _session;
|
||||
if (cached != null && cached.isDead) {
|
||||
// The worker isolate died; its port answers nothing. Spawn a fresh one
|
||||
// rather than hanging every later job on it.
|
||||
_session = null;
|
||||
_loadedBundle = null;
|
||||
} else if (cached != null && _loadedBundle == bundle) {
|
||||
return cached;
|
||||
}
|
||||
if (bundle == _failedBundle) {
|
||||
return null;
|
||||
|
||||
@@ -79,6 +79,11 @@ class ImageCodecSession {
|
||||
final Map<int, Completer<void>> _pendingReleases = {};
|
||||
int _nextJobId = 1;
|
||||
bool _disposed = false;
|
||||
bool _dead = false;
|
||||
|
||||
/// True once the worker isolate has died. A dead session can never answer
|
||||
/// again, so the owner must drop it and spawn a new one.
|
||||
bool get isDead => _dead;
|
||||
|
||||
ImageCodecSession._({
|
||||
required Isolate isolate,
|
||||
@@ -121,12 +126,16 @@ class ImageCodecSession {
|
||||
});
|
||||
|
||||
errors.listen((message) {
|
||||
final description = message is List && message.isNotEmpty
|
||||
// `null` is the onExit notification: the isolate is gone without an
|
||||
// error report (killed, or a native crash).
|
||||
final description = message == null
|
||||
? 'exited'
|
||||
: message is List && message.isNotEmpty
|
||||
? message.first.toString()
|
||||
: message.toString();
|
||||
final active = session;
|
||||
if (active != null) {
|
||||
active._failAll(StateError('Image codec isolate died: $description'));
|
||||
active._markDead(StateError('Image codec isolate died: $description'));
|
||||
} else if (!handshake.isCompleted) {
|
||||
handshake.complete({'type': 'fatal', 'error': description});
|
||||
}
|
||||
@@ -146,6 +155,7 @@ class ImageCodecSession {
|
||||
),
|
||||
errorsAreFatal: true,
|
||||
onError: errors.sendPort,
|
||||
onExit: errors.sendPort,
|
||||
debugName: 'image-codec',
|
||||
);
|
||||
} catch (_) {
|
||||
@@ -359,6 +369,18 @@ class ImageCodecSession {
|
||||
}
|
||||
}
|
||||
|
||||
/// The worker died on its own. Fail what is pending and refuse new work,
|
||||
/// or the next job would be sent to a dead port and wait forever.
|
||||
void _markDead(Object error) {
|
||||
if (_disposed) return;
|
||||
_dead = true;
|
||||
_disposed = true;
|
||||
_failAll(error);
|
||||
_isolate.kill(priority: Isolate.immediate);
|
||||
_fromWorker.close();
|
||||
_errors.close();
|
||||
}
|
||||
|
||||
/// Kills the isolate and frees the model's resident memory.
|
||||
Future<void> dispose() async {
|
||||
if (_disposed) return;
|
||||
|
||||
@@ -20,6 +20,8 @@ class ImageCodecSession {
|
||||
|
||||
bool get hasTables => false;
|
||||
|
||||
bool get isDead => false;
|
||||
|
||||
Future<void> release({bool decoder = false, bool entropy = false}) async {}
|
||||
|
||||
Future<Uint8List> decodeLatent(
|
||||
|
||||
@@ -26,7 +26,9 @@ class _AckHistoryEntry {
|
||||
/// for O(1) lookup. [pathSelection] snapshots the route used for this
|
||||
/// specific attempt so that a late PUSH_CODE_SEND_CONFIRMED credits the
|
||||
/// correct path even when the message has since been retried on a different
|
||||
/// route.
|
||||
/// route. Firmware hashes only `attempt & 3`, so attempts N and N+4 of one
|
||||
/// message share an ACK hash; each hash therefore keeps every attempt that
|
||||
/// produced it.
|
||||
typedef AckHashMapping = ({
|
||||
String messageId,
|
||||
DateTime timestamp,
|
||||
@@ -93,7 +95,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
final Map<String, Message> _pendingMessages = {};
|
||||
final Map<String, Contact> _pendingContacts = {};
|
||||
final Map<String, List<PathSelection>> _attemptPathHistory = {};
|
||||
final Map<String, AckHashMapping> _ackHashToMessageId = {};
|
||||
final Map<String, List<AckHashMapping>> _ackHashToMessageId = {};
|
||||
final Map<String, List<int>> _expectedAckHashes = {};
|
||||
final List<_AckHistoryEntry> _ackHistory = [];
|
||||
final Map<String, List<String>> _sendQueue = {};
|
||||
@@ -103,7 +105,11 @@ class MessageRetryService extends ChangeNotifier {
|
||||
|
||||
RetryServiceConfig? _config;
|
||||
|
||||
MessageRetryService();
|
||||
/// Extra time allowed for RESP_CODE_SENT on top of the delivery timeout
|
||||
/// before an attempt with no SENT reply is treated as timed out.
|
||||
final Duration sentWatchdogGrace;
|
||||
|
||||
MessageRetryService({this.sentWatchdogGrace = const Duration(seconds: 5)});
|
||||
|
||||
void initialize(RetryServiceConfig config) {
|
||||
_config = config;
|
||||
@@ -387,6 +393,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
if (config.getSelfPublicKey != null && selfPubKey == null) {
|
||||
throw StateError('Self public key unknown; cannot track ACK');
|
||||
}
|
||||
String? expectedHashHex;
|
||||
if (selfPubKey != null) {
|
||||
final outboundText =
|
||||
config.prepareContactOutboundText?.call(contact, message.text) ??
|
||||
@@ -397,7 +404,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
outboundText,
|
||||
selfPubKey,
|
||||
);
|
||||
final expectedHashHex = expectedHash.toRadixString(16).padLeft(8, '0');
|
||||
expectedHashHex = expectedHash.toRadixString(16).padLeft(8, '0');
|
||||
_expectedHashToMessageId[expectedHashHex] = messageId;
|
||||
|
||||
final shortText = message.text.length > 20
|
||||
@@ -410,6 +417,87 @@ class MessageRetryService extends ChangeNotifier {
|
||||
}
|
||||
|
||||
await config.sendMessage(contact, message.text, attempt, timestampSeconds);
|
||||
_startSentWatchdog(messageId, attempt, expectedHashHex);
|
||||
}
|
||||
|
||||
/// Arms a timer for an attempt whose RESP_CODE_SENT has not arrived yet.
|
||||
/// Without it a lost SENT reply leaves the message pending forever and
|
||||
/// blocks the contact's queue. A SENT reply replaces this timer with the
|
||||
/// normal ACK timeout via [_startTimeoutTimer].
|
||||
void _startSentWatchdog(
|
||||
String messageId,
|
||||
int attempt,
|
||||
String? expectedHashHex,
|
||||
) {
|
||||
final message = _pendingMessages[messageId];
|
||||
final contact = _pendingContacts[messageId];
|
||||
if (message == null || contact == null) return;
|
||||
if (_resolvedMessages.contains(messageId)) return;
|
||||
if (message.retryCount != attempt ||
|
||||
message.status != MessageStatus.pending) {
|
||||
return; // SENT already arrived, or a newer attempt took over.
|
||||
}
|
||||
if (_timeoutTimers[messageId]?.isActive ?? false) return;
|
||||
|
||||
final timeoutMs =
|
||||
_deliveryTimeoutFor(message, contact) +
|
||||
sentWatchdogGrace.inMilliseconds;
|
||||
_timeoutTimers[messageId] = Timer(Duration(milliseconds: timeoutMs), () {
|
||||
final current = _pendingMessages[messageId];
|
||||
if (current == null ||
|
||||
current.retryCount != attempt ||
|
||||
current.status != MessageStatus.pending) {
|
||||
return;
|
||||
}
|
||||
_config?.debugLogService?.warn(
|
||||
'No RESP_CODE_SENT for message $messageId (attempt $attempt) '
|
||||
'after ${timeoutMs}ms → treating as timed out',
|
||||
tag: 'AckHash',
|
||||
);
|
||||
if (expectedHashHex != null &&
|
||||
_expectedHashToMessageId[expectedHashHex] == messageId) {
|
||||
// Drop the SENT expectation so a late SENT for this attempt can't
|
||||
// restart timers for the retry; keep the hash ACK-matchable in case
|
||||
// the radio did transmit it.
|
||||
_expectedHashToMessageId.remove(expectedHashHex);
|
||||
_addAckHashMapping(expectedHashHex, messageId, current);
|
||||
final hash = int.parse(expectedHashHex, radix: 16);
|
||||
final hashes = _expectedAckHashes.putIfAbsent(messageId, () => []);
|
||||
if (!hashes.contains(hash)) hashes.add(hash);
|
||||
}
|
||||
_handleTimeout(messageId);
|
||||
});
|
||||
}
|
||||
|
||||
int _deliveryTimeoutFor(Message message, Contact contact) {
|
||||
final config = _config;
|
||||
final calculate = config?.calculateTimeout;
|
||||
if (calculate == null) return calculateDefaultTimeout(contact);
|
||||
final outboundText =
|
||||
config?.prepareContactOutboundText?.call(contact, message.text) ??
|
||||
message.text;
|
||||
return calculate(
|
||||
message.pathLength ?? contact.pathLength,
|
||||
utf8.encode(outboundText).length,
|
||||
contactKey: contact.publicKeyHex,
|
||||
);
|
||||
}
|
||||
|
||||
void _addAckHashMapping(
|
||||
String ackHashHex,
|
||||
String messageId,
|
||||
Message message,
|
||||
) {
|
||||
final mappings = _ackHashToMessageId.putIfAbsent(ackHashHex, () => []);
|
||||
mappings.removeWhere(
|
||||
(m) => m.messageId == messageId && m.attemptIndex == message.retryCount,
|
||||
);
|
||||
mappings.add((
|
||||
messageId: messageId,
|
||||
timestamp: DateTime.now(),
|
||||
attemptIndex: message.retryCount,
|
||||
pathSelection: _selectionFromMessage(message),
|
||||
));
|
||||
}
|
||||
|
||||
bool updateMessageFromSent(int ackHash, int timeoutMs) {
|
||||
@@ -454,12 +542,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
}
|
||||
|
||||
final message = _pendingMessages[messageId]!;
|
||||
_ackHashToMessageId[ackHashHex] = (
|
||||
messageId: messageId,
|
||||
timestamp: DateTime.now(),
|
||||
attemptIndex: message.retryCount,
|
||||
pathSelection: _selectionFromMessage(message),
|
||||
);
|
||||
_addAckHashMapping(ackHashHex, messageId, message);
|
||||
|
||||
// Add this ACK hash to the list of expected ACKs for this message (for history)
|
||||
_expectedAckHashes[messageId] ??= [];
|
||||
@@ -526,9 +609,10 @@ class MessageRetryService extends ChangeNotifier {
|
||||
|
||||
void _cleanupMessage(String messageId) {
|
||||
_moveAckHashesToHistory(messageId);
|
||||
_ackHashToMessageId.removeWhere(
|
||||
(_, mapping) => mapping.messageId == messageId,
|
||||
);
|
||||
_ackHashToMessageId.removeWhere((_, mappings) {
|
||||
mappings.removeWhere((mapping) => mapping.messageId == messageId);
|
||||
return mappings.isEmpty;
|
||||
});
|
||||
_expectedHashToMessageId.removeWhere((_, msgId) => msgId == messageId);
|
||||
final contactKey = _pendingContacts[messageId]?.publicKeyHex;
|
||||
_pendingMessages.remove(messageId);
|
||||
@@ -672,26 +756,30 @@ class MessageRetryService extends ChangeNotifier {
|
||||
String? matchedMessageId;
|
||||
int? matchedAttemptIndex;
|
||||
PathSelection? matchedPathSelection;
|
||||
// True when attempts on different routes share this ACK hash, so the
|
||||
// route that delivered it is unknown and must not be credited.
|
||||
var ambiguousPath = false;
|
||||
final ackHashHex = ackHash.toRadixString(16).padLeft(8, '0');
|
||||
|
||||
// Clean up old ACK hash mappings (older than 15 minutes)
|
||||
final cutoffTime = DateTime.now().subtract(const Duration(minutes: 15));
|
||||
final hashesToRemove = <String>[];
|
||||
for (var entry in _ackHashToMessageId.entries) {
|
||||
if (entry.value.timestamp.isBefore(cutoffTime)) {
|
||||
hashesToRemove.add(entry.key);
|
||||
}
|
||||
}
|
||||
for (var hash in hashesToRemove) {
|
||||
_ackHashToMessageId.remove(hash);
|
||||
}
|
||||
_ackHashToMessageId.removeWhere((_, mappings) {
|
||||
mappings.removeWhere((m) => m.timestamp.isBefore(cutoffTime));
|
||||
return mappings.isEmpty;
|
||||
});
|
||||
|
||||
// Use direct O(1) lookup via ACK hash mapping
|
||||
final mapping = _ackHashToMessageId[ackHashHex];
|
||||
if (mapping != null) {
|
||||
final mappings = _ackHashToMessageId[ackHashHex];
|
||||
if (mappings != null && mappings.isNotEmpty) {
|
||||
final mapping = mappings.first;
|
||||
matchedMessageId = mapping.messageId;
|
||||
matchedAttemptIndex = mapping.attemptIndex;
|
||||
matchedPathSelection = mapping.pathSelection;
|
||||
ambiguousPath = mappings.any(
|
||||
(m) =>
|
||||
m.messageId != mapping.messageId ||
|
||||
!_sameSelection(m.pathSelection, mapping.pathSelection),
|
||||
);
|
||||
} else {
|
||||
config?.debugLogService?.warn(
|
||||
'PUSH_CODE_SEND_CONFIRMED: ACK hash $ackHashHex not found in direct mapping, trying fallback',
|
||||
@@ -746,13 +834,15 @@ class MessageRetryService extends ChangeNotifier {
|
||||
config?.updateMessage(deliveredMessage);
|
||||
|
||||
if (contact != null) {
|
||||
_recordPathResultFromMessage(
|
||||
contact.publicKeyHex,
|
||||
message,
|
||||
selection,
|
||||
true,
|
||||
tripTimeMs,
|
||||
);
|
||||
if (!ambiguousPath) {
|
||||
_recordPathResultFromMessage(
|
||||
contact.publicKeyHex,
|
||||
message,
|
||||
selection,
|
||||
true,
|
||||
tripTimeMs,
|
||||
);
|
||||
}
|
||||
if (config?.onDeliveryObserved != null &&
|
||||
tripTimeMs > 0 &&
|
||||
message.pathLength != null) {
|
||||
@@ -825,6 +915,13 @@ class MessageRetryService extends ChangeNotifier {
|
||||
callback(contactKey, recordSelection, success, tripTimeMs);
|
||||
}
|
||||
|
||||
static bool _sameSelection(PathSelection? a, PathSelection? b) {
|
||||
if (a == null || b == null) return a == b;
|
||||
return a.useFlood == b.useFlood &&
|
||||
a.hopCount == b.hopCount &&
|
||||
listEquals(a.pathBytes, b.pathBytes);
|
||||
}
|
||||
|
||||
PathSelection? _selectionFromMessage(Message message) {
|
||||
if (message.pathLength != null && message.pathLength! < 0) {
|
||||
return const PathSelection(pathBytes: [], hopCount: -1, useFlood: true);
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'dart:ui';
|
||||
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
||||
|
||||
import '../helpers/message_url_image_helper.dart';
|
||||
@@ -624,6 +625,7 @@ class NotificationService {
|
||||
Future<void> cancelAll() async {
|
||||
_conversations.clear();
|
||||
await _notifications.cancelAll();
|
||||
await _updateBadge(0);
|
||||
}
|
||||
|
||||
Future<void> cancel(int id) async {
|
||||
@@ -660,28 +662,22 @@ class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
static const MethodChannel _badgeChannel = MethodChannel(
|
||||
'meshcore_open/app_badge',
|
||||
);
|
||||
|
||||
/// Sets the app icon badge to the current unread total.
|
||||
Future<void> setAppBadge(int count) => _updateBadge(count);
|
||||
|
||||
Future<void> _updateBadge(int count) async {
|
||||
if (PlatformInfo.isIOS || PlatformInfo.isMacOS) {
|
||||
// On Apple platforms, set the badge number directly via a silent update.
|
||||
final darwinDetails = DarwinNotificationDetails(
|
||||
presentAlert: false,
|
||||
presentSound: false,
|
||||
presentBadge: true,
|
||||
badgeNumber: count,
|
||||
);
|
||||
final details = NotificationDetails(
|
||||
iOS: darwinDetails,
|
||||
macOS: darwinDetails,
|
||||
);
|
||||
// Use a fixed ID so each update replaces the previous one.
|
||||
await _notifications.show(
|
||||
id: 'badge_update'.hashCode,
|
||||
title: null,
|
||||
body: null,
|
||||
notificationDetails: details,
|
||||
);
|
||||
// Immediately cancel the silent notification so it doesn't appear in tray.
|
||||
await _notifications.cancel(id: 'badge_update'.hashCode);
|
||||
// Set natively: a silent notification cancelled right after show() is
|
||||
// removed before iOS delivers it, so its badge number never applied.
|
||||
try {
|
||||
await _badgeChannel.invokeMethod<void>('setBadgeCount', count);
|
||||
} catch (e) {
|
||||
debugPrint('Failed to update app badge: $e');
|
||||
}
|
||||
}
|
||||
// On Android, badge count is derived from active notifications,
|
||||
// so cancelling the specific notification above is sufficient.
|
||||
|
||||
@@ -118,7 +118,7 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _write(
|
||||
Future<bool> _write(
|
||||
String streamId,
|
||||
String extension,
|
||||
Uint8List bytes,
|
||||
@@ -127,13 +127,17 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
final path = await _pathFor(streamId, extension);
|
||||
if (path == null) {
|
||||
debugPrint('received_image_blob_store: refusing unsafe id "$streamId"');
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
await File(path).writeAsBytes(bytes, flush: true);
|
||||
return true;
|
||||
} catch (error) {
|
||||
debugPrint(
|
||||
'received_image_blob_store: write $streamId$extension: $error',
|
||||
);
|
||||
// A partial file would be counted as stored by the next startup scan.
|
||||
await _delete(streamId, extension);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,7 +167,7 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> writeBitstream(String streamId, Uint8List bytes) =>
|
||||
Future<bool> writeBitstream(String streamId, Uint8List bytes) =>
|
||||
_write(streamId, _bitstreamExt, bytes);
|
||||
|
||||
@override
|
||||
@@ -178,7 +182,7 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
Future<int?> bitstreamSize(String streamId) => _size(streamId, _bitstreamExt);
|
||||
|
||||
@override
|
||||
Future<void> writePng(String streamId, Uint8List bytes) =>
|
||||
Future<bool> writePng(String streamId, Uint8List bytes) =>
|
||||
_write(streamId, _pngExt, bytes);
|
||||
|
||||
@override
|
||||
|
||||
@@ -374,11 +374,14 @@ class ReceivedImageEntry {
|
||||
/// `received_images/<streamId>.aeic|.png|.json`. See
|
||||
/// `received_image_blob_store_io.dart`.
|
||||
abstract class ReceivedImageBlobStore {
|
||||
Future<void> writeBitstream(String streamId, Uint8List bytes);
|
||||
/// Returns false when the bytes could not be stored (disk full, unsafe id),
|
||||
/// so the caller never records a file that is not there.
|
||||
Future<bool> writeBitstream(String streamId, Uint8List bytes);
|
||||
Future<Uint8List?> readBitstream(String streamId);
|
||||
Future<void> deleteBitstream(String streamId);
|
||||
|
||||
Future<void> writePng(String streamId, Uint8List bytes);
|
||||
/// Same contract as [writeBitstream].
|
||||
Future<bool> writePng(String streamId, Uint8List bytes);
|
||||
Future<Uint8List?> readPng(String streamId);
|
||||
Future<void> deletePng(String streamId);
|
||||
|
||||
@@ -418,8 +421,9 @@ class InMemoryReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
final Map<String, String> _sidecars = <String, String>{};
|
||||
|
||||
@override
|
||||
Future<void> writeBitstream(String streamId, Uint8List bytes) async {
|
||||
Future<bool> writeBitstream(String streamId, Uint8List bytes) async {
|
||||
_bitstreams[streamId] = bytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -439,8 +443,9 @@ class InMemoryReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
Future<int?> pngSize(String streamId) async => _pngs[streamId]?.length;
|
||||
|
||||
@override
|
||||
Future<void> writePng(String streamId, Uint8List bytes) async {
|
||||
Future<bool> writePng(String streamId, Uint8List bytes) async {
|
||||
_pngs[streamId] = bytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -551,6 +556,11 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
/// Hard cap on stored PNGs.
|
||||
final int maxImages;
|
||||
|
||||
/// Hard cap on entries of any state. Undecoded entries hold no PNG, so
|
||||
/// [maxImages] never counts them; without this a flood of one-packet images
|
||||
/// grows the sidecars (and the startup scan) without bound.
|
||||
final int maxEntries;
|
||||
|
||||
/// Hard cap on total bytes across all stored files.
|
||||
final int maxBytes;
|
||||
|
||||
@@ -599,6 +609,10 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
/// Set by [handleMemoryPressure] so the decode it cancels is parked rather
|
||||
/// than reported as corrupt.
|
||||
bool _cancelRequested = false;
|
||||
|
||||
/// Set by [setForeground] when backgrounding cancels a running decode, so it
|
||||
/// goes back on the queue instead of being reported as corrupt.
|
||||
bool _backgroundCancelled = false;
|
||||
bool _foreground = true;
|
||||
bool _disposed = false;
|
||||
|
||||
@@ -606,6 +620,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
ReceivedImageBlobStore? blobs,
|
||||
this.decoder,
|
||||
this.maxImages = 200,
|
||||
this.maxEntries = 400,
|
||||
this.maxBytes = 64 * 1024 * 1024,
|
||||
this.maxAge = const Duration(days: 30),
|
||||
this.burstCap = 3,
|
||||
@@ -727,7 +742,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
}
|
||||
|
||||
_entries[entry.streamId] = entry;
|
||||
_byKey[entry.key] = entry.streamId;
|
||||
_claimKey(entry);
|
||||
_publish(entry);
|
||||
await _persist(entry);
|
||||
}
|
||||
@@ -877,9 +892,46 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
}
|
||||
|
||||
final metadata = result.metadata;
|
||||
// The reserved high rate (ft16) and any resolution but 512 cannot be
|
||||
// decoded by the only model this build ships; storing them as
|
||||
// `reassembled` would end in an endless "corrupt, retry" loop. Treat them
|
||||
// like an undecodable metadata byte: nothing to retry, no bytes kept.
|
||||
if (metadata != null &&
|
||||
(metadata.rate != ImageCodecRatePoint.standard ||
|
||||
metadata.squareSize != kImageCodecSquareSize)) {
|
||||
_queue.remove(entry.streamId);
|
||||
return _store(
|
||||
entry.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
receivedChunks: result.chunkCount,
|
||||
totalChunks: result.chunkCount,
|
||||
bitstreamStored: false,
|
||||
error: 'Unsupported image format.',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final tracked = _entries.containsKey(entry.streamId);
|
||||
// Bitstream first, state second: a kill between the two must be
|
||||
// recoverable, and `reassembled` with no file on disk is a lie.
|
||||
await blobs.writeBitstream(entry.streamId, result.data);
|
||||
final written = await blobs.writeBitstream(entry.streamId, result.data);
|
||||
if (tracked && !_entries.containsKey(entry.streamId)) {
|
||||
// Deleted (message removed, channel cleared) while the write was in
|
||||
// flight. Storing now would resurrect it with no message to show it.
|
||||
await blobs.deleteBitstream(entry.streamId);
|
||||
return entry;
|
||||
}
|
||||
if (!written) {
|
||||
return _store(
|
||||
entry.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
receivedChunks: result.chunkCount,
|
||||
totalChunks: result.chunkCount,
|
||||
bitstreamStored: false,
|
||||
error: 'Could not save the image data.',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final updated = entry.copyWith(
|
||||
state: ReceivedImageState.reassembled,
|
||||
@@ -900,9 +952,12 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
// Park it: the card shows "N bytes · M packets" and "Tap to process".
|
||||
// A 2.16 GiB decode is never started off the back of a radio packet
|
||||
// unless the user asked for that.
|
||||
return _store(updated.copyWith(needsManualDecode: true));
|
||||
final parked = await _store(updated.copyWith(needsManualDecode: true));
|
||||
await _enforceEntryCap(protect: parked.streamId);
|
||||
return parked;
|
||||
}
|
||||
final stored = await _store(updated);
|
||||
await _enforceEntryCap(protect: stored.streamId);
|
||||
_enqueue(stored.streamId);
|
||||
return stored;
|
||||
}
|
||||
@@ -965,6 +1020,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
required Uint8List previewPng,
|
||||
required AeicRatePoint rate,
|
||||
required int chunkCount,
|
||||
int aspectCode = 0,
|
||||
DateTime? at,
|
||||
}) async {
|
||||
final now = at ?? _clock();
|
||||
@@ -973,7 +1029,10 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
imgId: imgId,
|
||||
firstSeen: now,
|
||||
);
|
||||
await blobs.writePng(streamId, previewPng);
|
||||
// A failed write still shows the photo for this session (the bytes stay
|
||||
// cached on the entry); the next launch then reports it as evicted rather
|
||||
// than pointing at a file that was never written.
|
||||
final pngWritten = await blobs.writePng(streamId, previewPng);
|
||||
final entry = ReceivedImageEntry(
|
||||
streamId: streamId,
|
||||
senderPrefix: senderPrefix,
|
||||
@@ -984,10 +1043,13 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
receivedChunks: chunkCount,
|
||||
totalChunks: chunkCount,
|
||||
rate: rate,
|
||||
// The preview is the same stretched 512x512 square the receiver gets,
|
||||
// so the sender's bubble needs the source shape to undo it too.
|
||||
aspectCode: aspectCode,
|
||||
metadataAssumed: false,
|
||||
isOutgoing: true,
|
||||
pngStored: true,
|
||||
pngByteCount: previewPng.length,
|
||||
pngStored: pngWritten,
|
||||
pngByteCount: pngWritten ? previewPng.length : 0,
|
||||
pngBytes: previewPng,
|
||||
);
|
||||
final stored = await _store(entry);
|
||||
@@ -1003,7 +1065,12 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
if (_foreground == value) return;
|
||||
_foreground = value;
|
||||
if (!value) {
|
||||
decoder?.cancelCodecJob();
|
||||
// Only cancel OUR decode: the codec is shared with the send sheet, and an
|
||||
// encode it is running is not this store's to stop.
|
||||
if (_decodeInFlight) {
|
||||
_backgroundCancelled = true;
|
||||
decoder?.cancelCodecJob();
|
||||
}
|
||||
} else {
|
||||
_parkedOnBusyDecoder = false;
|
||||
_kick();
|
||||
@@ -1193,9 +1260,14 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
ReceivedImageDecoder decoder,
|
||||
) async {
|
||||
final bitstream = await blobs.readBitstream(entry.streamId);
|
||||
// Every await below is a window in which the user may delete the image
|
||||
// (message removed, channel cleared). Re-read the live entry after each
|
||||
// one and stop if it is gone, or the decode would store it back.
|
||||
final live = _entries[entry.streamId];
|
||||
if (live == null) return;
|
||||
if (bitstream == null || bitstream.isEmpty) {
|
||||
await _store(
|
||||
entry.copyWith(
|
||||
live.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
bitstreamStored: false,
|
||||
error: 'Bitstream missing.',
|
||||
@@ -1205,49 +1277,34 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
}
|
||||
final started = _clock();
|
||||
_cancelRequested = false;
|
||||
await _store(entry.copyWith(state: ReceivedImageState.decoding));
|
||||
_backgroundCancelled = false;
|
||||
await _store(live.copyWith(state: ReceivedImageState.decoding));
|
||||
|
||||
ImageCodecResult? result;
|
||||
Object? failure;
|
||||
try {
|
||||
result = await decoder.decodeBitstream(
|
||||
bitstream: bitstream,
|
||||
ratePoint: entry.rate,
|
||||
resolution: entry.resolution,
|
||||
ratePoint: live.rate,
|
||||
resolution: live.resolution,
|
||||
);
|
||||
} catch (error) {
|
||||
final current = _entries[entry.streamId] ?? entry;
|
||||
if (_cancelRequested) {
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.reassembled,
|
||||
needsManualDecode: true,
|
||||
),
|
||||
);
|
||||
} else if (!_foreground) {
|
||||
await _store(current.copyWith(state: ReceivedImageState.reassembled));
|
||||
} else {
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
error: error.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
failure = error;
|
||||
}
|
||||
|
||||
final current = _entries[entry.streamId] ?? entry;
|
||||
if (result == null) {
|
||||
// canDecode false — the codec cannot run at all.
|
||||
await _store(
|
||||
current.copyWith(state: ReceivedImageState.decoderUnavailable),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final png = result.pngBytes;
|
||||
if (result.status != ImageCodecStatus.completed || png == null) {
|
||||
final current = _entries[entry.streamId];
|
||||
if (current == null) return;
|
||||
final png = result?.pngBytes;
|
||||
final completed =
|
||||
failure == null &&
|
||||
result != null &&
|
||||
result.status == ImageCodecStatus.completed &&
|
||||
png != null;
|
||||
|
||||
if (!completed) {
|
||||
if (_cancelRequested) {
|
||||
// The codec reports a killed job as `failed`; the bitstream is fine.
|
||||
// Memory pressure: the codec reports a killed job as `failed`, but
|
||||
// the bitstream is fine. Park it behind a tap.
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.reassembled,
|
||||
@@ -1256,27 +1313,47 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (_backgroundCancelled || !_foreground) {
|
||||
// Backgrounded mid-decode: back to the front of the queue, so coming
|
||||
// back to the app picks it up again.
|
||||
await _store(current.copyWith(state: ReceivedImageState.reassembled));
|
||||
if (!_queue.contains(current.streamId)) {
|
||||
_queue.insert(0, current.streamId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (failure == null && result == null) {
|
||||
// canDecode false — the codec cannot run at all.
|
||||
await _store(
|
||||
current.copyWith(state: ReceivedImageState.decoderUnavailable),
|
||||
);
|
||||
return;
|
||||
}
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
error: 'Decoder rejected the bitstream.',
|
||||
error: failure?.toString() ?? 'Decoder rejected the bitstream.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!_foreground) {
|
||||
// Backgrounded mid-decode: keep the pixels, but do not claim a decode we
|
||||
// may have half-cancelled.
|
||||
await _store(current.copyWith(state: ReceivedImageState.reassembled));
|
||||
|
||||
// A completed result is a finished decode even if the app went to the
|
||||
// background in the meantime; throwing the pixels away would only make
|
||||
// the user wait for a second 2 GiB run.
|
||||
final written = await blobs.writePng(current.streamId, png);
|
||||
final afterWrite = _entries[entry.streamId];
|
||||
if (afterWrite == null) {
|
||||
await blobs.deletePng(current.streamId);
|
||||
return;
|
||||
}
|
||||
|
||||
await blobs.writePng(current.streamId, png);
|
||||
await _store(
|
||||
current.copyWith(
|
||||
afterWrite.copyWith(
|
||||
state: ReceivedImageState.decoded,
|
||||
pngStored: true,
|
||||
pngByteCount: png.length,
|
||||
// A failed write keeps the pixels cached for this session; the next
|
||||
// launch reports the image as evicted ("Decode again") instead.
|
||||
pngStored: written,
|
||||
pngByteCount: written ? png.length : 0,
|
||||
pngBytes: png,
|
||||
decodeMs: result.durationMs > 0
|
||||
? result.durationMs
|
||||
@@ -1288,7 +1365,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
// Without `protect` the freshly decoded image is the budget's own victim
|
||||
// whenever it is also the oldest: decode -> evict -> "Decode again" ->
|
||||
// evict, forever.
|
||||
await evictToBudget(protect: current.streamId);
|
||||
await evictToBudget(protect: afterWrite.streamId);
|
||||
}
|
||||
|
||||
// ---- pixels --------------------------------------------------------------
|
||||
@@ -1330,7 +1407,10 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
Future<void> deleteImage(String streamId) async {
|
||||
final entry = _entries.remove(streamId);
|
||||
_queue.remove(streamId);
|
||||
if (entry != null) {
|
||||
// Only unlink the key if it still points here: a newer image reusing the
|
||||
// same sender/id/channel owns it now, and losing that mapping strands the
|
||||
// newer one on "receiving" while its next chunk opens a third entry.
|
||||
if (entry != null && _byKey[entry.key] == streamId) {
|
||||
_byKey.remove(entry.key);
|
||||
}
|
||||
await blobs.deletePng(streamId);
|
||||
@@ -1468,10 +1548,50 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
evicted.addAll(await _enforceEntryCap(protect: protect));
|
||||
|
||||
if (evicted.isNotEmpty) _notify();
|
||||
return evicted;
|
||||
}
|
||||
|
||||
/// Brings the entry count inside [maxEntries], oldest first: failures, then
|
||||
/// entries with nothing left on disk, then undecoded incoming images. Never
|
||||
/// touches outgoing images, a running decode or a stream still receiving.
|
||||
Future<List<String>> _enforceEntryCap({String? protect}) async {
|
||||
final removed = <String>[];
|
||||
if (_entries.length <= maxEntries) return removed;
|
||||
int rank(ReceivedImageEntry e) {
|
||||
if (e.state.isFailure) return 0;
|
||||
if (e.state == ReceivedImageState.evicted && !e.bitstreamStored) {
|
||||
return 1;
|
||||
}
|
||||
return 2;
|
||||
}
|
||||
|
||||
final victims =
|
||||
_entries.values
|
||||
.where(
|
||||
(e) =>
|
||||
e.streamId != protect &&
|
||||
!e.isOutgoing &&
|
||||
(e.state.isFailure ||
|
||||
e.state == ReceivedImageState.evicted ||
|
||||
e.state == ReceivedImageState.reassembled ||
|
||||
e.state == ReceivedImageState.decoderUnavailable),
|
||||
)
|
||||
.toList()
|
||||
..sort((a, b) {
|
||||
final byRank = rank(a).compareTo(rank(b));
|
||||
return byRank != 0 ? byRank : a.firstSeen.compareTo(b.firstSeen);
|
||||
});
|
||||
for (final victim in victims) {
|
||||
if (_entries.length <= maxEntries) break;
|
||||
await deleteImage(victim.streamId);
|
||||
removed.add(victim.streamId);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
// ---- plumbing ------------------------------------------------------------
|
||||
|
||||
String _uniqueStreamId({
|
||||
@@ -1507,11 +1627,25 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
|
||||
void _storeSync(ReceivedImageEntry entry) {
|
||||
_entries[entry.streamId] = entry;
|
||||
_byKey[entry.key] = entry.streamId;
|
||||
_claimKey(entry);
|
||||
_publish(entry);
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// Points the entry's key at it unless a newer image already holds the key.
|
||||
/// Updating an old entry (eviction, a late decode) must not steal the key
|
||||
/// back from a newer stream that reused the same 8-bit id.
|
||||
void _claimKey(ReceivedImageEntry entry) {
|
||||
final holderId = _byKey[entry.key];
|
||||
if (holderId != null && holderId != entry.streamId) {
|
||||
final holder = _entries[holderId];
|
||||
if (holder != null && holder.firstSeen.isAfter(entry.firstSeen)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
_byKey[entry.key] = entry.streamId;
|
||||
}
|
||||
|
||||
Future<void> _persist(ReceivedImageEntry entry) async {
|
||||
try {
|
||||
await blobs.writeSidecar(entry.streamId, jsonEncode(entry.toJson()));
|
||||
|
||||
@@ -14,12 +14,21 @@ String normalizeRepeaterClockSyncCommand(String command, {int? nowSeconds}) {
|
||||
return command.trim().toLowerCase() == 'clock sync' ? 'time $epoch' : command;
|
||||
}
|
||||
|
||||
/// One [RepeaterCommandService.sendCommand] call. Every retry adds a fresh
|
||||
/// `XX|` prefix, and a reply to any of them completes the call, so a late
|
||||
/// reply to an earlier attempt is not mistaken for silence.
|
||||
class _PendingCommand {
|
||||
_PendingCommand(this.repeaterKey);
|
||||
|
||||
final String repeaterKey;
|
||||
final Completer<String> completer = Completer<String>();
|
||||
final Set<String> prefixes = {};
|
||||
}
|
||||
|
||||
class RepeaterCommandService {
|
||||
final MeshCoreConnector _connector;
|
||||
final Map<String, Completer<String>> _pendingCommands = {};
|
||||
final Map<String, Timer> _commandTimeouts = {};
|
||||
final Map<String, String> _commandPrefixes = {};
|
||||
final Map<String, String> _pendingByPrefix = {};
|
||||
final Set<_PendingCommand> _pendingCommands = {};
|
||||
final Map<String, _PendingCommand> _pendingByPrefix = {};
|
||||
int _prefixCounter = 0;
|
||||
|
||||
static const int maxRetries = 5;
|
||||
@@ -40,26 +49,33 @@ class RepeaterCommandService {
|
||||
}) async {
|
||||
if (!raw) command = normalizeRepeaterClockSyncCommand(command);
|
||||
final attemptCount = retries < 1 ? 1 : retries;
|
||||
final selection = await _connector.preparePathForContactSend(repeater);
|
||||
final pending = _PendingCommand(repeater.publicKeyHex);
|
||||
_pendingCommands.add(pending);
|
||||
try {
|
||||
final selection = await _connector.preparePathForContactSend(repeater);
|
||||
|
||||
for (int attempt = 0; attempt < attemptCount; attempt++) {
|
||||
onAttempt?.call(attempt + 1);
|
||||
try {
|
||||
final response = await _sendCommandAttempt(
|
||||
repeater,
|
||||
command,
|
||||
selection,
|
||||
attempt,
|
||||
raw,
|
||||
);
|
||||
onResponse?.call(response);
|
||||
return response;
|
||||
} catch (e) {
|
||||
if (attempt == attemptCount - 1) rethrow;
|
||||
for (int attempt = 0; attempt < attemptCount; attempt++) {
|
||||
onAttempt?.call(attempt + 1);
|
||||
try {
|
||||
final response = await _sendCommandAttempt(
|
||||
repeater,
|
||||
command,
|
||||
selection,
|
||||
attempt,
|
||||
raw,
|
||||
pending,
|
||||
);
|
||||
onResponse?.call(response);
|
||||
return response;
|
||||
} catch (e) {
|
||||
if (attempt == attemptCount - 1) rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw Exception('Command failed after $attemptCount attempts');
|
||||
throw Exception('Command failed after $attemptCount attempts');
|
||||
} finally {
|
||||
_cleanup(pending);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> _sendCommandAttempt(
|
||||
@@ -68,15 +84,16 @@ class RepeaterCommandService {
|
||||
PathSelection selection,
|
||||
int attempt,
|
||||
bool raw,
|
||||
_PendingCommand pending,
|
||||
) async {
|
||||
final repeaterKey = repeater.publicKeyHex;
|
||||
final prefix = _nextPrefixToken();
|
||||
final commandId = '${repeaterKey}_$prefix';
|
||||
final completer = Completer<String>();
|
||||
_pendingCommands[commandId] = completer;
|
||||
_commandPrefixes[commandId] = prefix;
|
||||
_pendingByPrefix[prefix] = commandId;
|
||||
// A reply to an earlier attempt may have arrived during the backoff.
|
||||
if (pending.completer.isCompleted) return pending.completer.future;
|
||||
|
||||
final prefix = _nextPrefixToken();
|
||||
pending.prefixes.add(prefix);
|
||||
_pendingByPrefix[prefix] = pending;
|
||||
|
||||
final int timeoutMs;
|
||||
try {
|
||||
final framedCommand = raw ? command : '$prefix$command';
|
||||
final pathLengthValue = selection.useFlood ? -1 : selection.hopCount;
|
||||
@@ -97,35 +114,21 @@ class RepeaterCommandService {
|
||||
final responseBytes = frame.length > maxFrameSize
|
||||
? frame.length
|
||||
: maxFrameSize;
|
||||
final timeoutMs = _connector.calculateTimeout(
|
||||
timeoutMs = _connector.calculateTimeout(
|
||||
pathLength: pathLengthValue,
|
||||
messageBytes: responseBytes,
|
||||
);
|
||||
final timeoutSeconds = (timeoutMs / 1000).ceil();
|
||||
await _connector.sendFrame(frame);
|
||||
_commandTimeouts[commandId]?.cancel();
|
||||
_commandTimeouts[commandId] = Timer(
|
||||
Duration(milliseconds: timeoutMs),
|
||||
() {
|
||||
final completer = _pendingCommands[commandId];
|
||||
if (completer != null && !completer.isCompleted) {
|
||||
completer.completeError(
|
||||
'Command timeout after $timeoutSeconds seconds',
|
||||
);
|
||||
_cleanup(commandId);
|
||||
}
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_cleanup(commandId);
|
||||
throw Exception('Failed to send command: $e');
|
||||
}
|
||||
|
||||
try {
|
||||
return await completer.future;
|
||||
} finally {
|
||||
_cleanup(commandId);
|
||||
}
|
||||
final timeoutSeconds = (timeoutMs / 1000).ceil();
|
||||
return pending.completer.future.timeout(
|
||||
Duration(milliseconds: timeoutMs),
|
||||
onTimeout: () =>
|
||||
Future<String>.error('Command timeout after $timeoutSeconds seconds'),
|
||||
);
|
||||
}
|
||||
|
||||
/// Send [line] verbatim and don't wait for a reply. While `region load` is
|
||||
@@ -142,48 +145,43 @@ class RepeaterCommandService {
|
||||
// Find pending command for this repeater and complete it
|
||||
final repeaterKey = repeater.publicKeyHex;
|
||||
|
||||
String? commandId;
|
||||
_PendingCommand? pending;
|
||||
String responsePayload = responseText;
|
||||
if (_prefixPattern.hasMatch(responseText)) {
|
||||
final prefix = responseText.substring(0, 3).toUpperCase();
|
||||
commandId = _pendingByPrefix[prefix];
|
||||
if (commandId == null || !commandId.startsWith('${repeaterKey}_')) {
|
||||
pending = _pendingByPrefix[prefix];
|
||||
if (pending == null || pending.repeaterKey != repeaterKey) {
|
||||
return;
|
||||
}
|
||||
responsePayload = responseText.substring(3).trimLeft();
|
||||
}
|
||||
|
||||
commandId ??= _pendingCommands.keys.firstWhere(
|
||||
(id) => id.startsWith('${repeaterKey}_'),
|
||||
orElse: () => '',
|
||||
);
|
||||
if (pending == null) {
|
||||
for (final candidate in _pendingCommands) {
|
||||
if (candidate.repeaterKey == repeaterKey &&
|
||||
!candidate.completer.isCompleted) {
|
||||
pending = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (commandId.isEmpty) return;
|
||||
|
||||
final completer = _pendingCommands[commandId];
|
||||
if (completer != null && !completer.isCompleted) {
|
||||
completer.complete(responsePayload);
|
||||
_cleanup(commandId);
|
||||
if (pending != null && !pending.completer.isCompleted) {
|
||||
pending.completer.complete(responsePayload);
|
||||
}
|
||||
}
|
||||
|
||||
void _cleanup(String commandId) {
|
||||
_commandTimeouts[commandId]?.cancel();
|
||||
_commandTimeouts.remove(commandId);
|
||||
_pendingCommands.remove(commandId);
|
||||
final prefix = _commandPrefixes.remove(commandId);
|
||||
if (prefix != null) {
|
||||
_pendingByPrefix.remove(prefix);
|
||||
void _cleanup(_PendingCommand pending) {
|
||||
_pendingCommands.remove(pending);
|
||||
for (final prefix in pending.prefixes) {
|
||||
if (identical(_pendingByPrefix[prefix], pending)) {
|
||||
_pendingByPrefix.remove(prefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
for (final timer in _commandTimeouts.values) {
|
||||
timer.cancel();
|
||||
}
|
||||
_commandTimeouts.clear();
|
||||
_pendingCommands.clear();
|
||||
_commandPrefixes.clear();
|
||||
_pendingByPrefix.clear();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:convert';
|
||||
import '../models/delivery_observation.dart';
|
||||
import '../models/path_history.dart';
|
||||
import '../storage/legacy_key_migration.dart';
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
@@ -12,6 +13,13 @@ class StorageService {
|
||||
'repeater_auto_clock_sync_after_login';
|
||||
static const String _deliveryObservationsKey = 'delivery_observations';
|
||||
|
||||
/// App-wide keys (not scoped to a radio) that hold per-repeater data. Review
|
||||
/// mode snapshots and restores them so simulated logins leave nothing behind.
|
||||
static const List<String> globalRepeaterKeys = [
|
||||
_repeaterPasswordsKey,
|
||||
_repeaterAutoClockSyncAfterLoginKey,
|
||||
];
|
||||
|
||||
String _publicKeyHex = '';
|
||||
set setPublicKeyHex(String value) =>
|
||||
_publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
|
||||
@@ -65,10 +73,22 @@ class StorageService {
|
||||
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
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');
|
||||
var jsonStr = prefs.getString(key);
|
||||
final legacyKey = '$_pathHistoryPrefix$contactPubKeyHex';
|
||||
if (jsonStr == null &&
|
||||
_publicKeyHex.isNotEmpty &&
|
||||
canMigrateLegacyKeys(_publicKeyHex)) {
|
||||
// Move the pre-scoping history into the first radio that loads it so
|
||||
// learned routes survive the upgrade without leaking into other radios.
|
||||
final legacy = prefs.getString(legacyKey);
|
||||
if (legacy != null) {
|
||||
await prefs.setString(key, legacy);
|
||||
await prefs.remove(legacyKey);
|
||||
jsonStr = legacy;
|
||||
}
|
||||
} else if (jsonStr == null && _publicKeyHex.isEmpty) {
|
||||
jsonStr = prefs.getString(legacyKey);
|
||||
}
|
||||
|
||||
if (jsonStr == null) return null;
|
||||
|
||||
@@ -86,12 +106,23 @@ class StorageService {
|
||||
await prefs.remove('$_pathHistoryPrefix$contactPubKeyHex');
|
||||
}
|
||||
|
||||
/// Clears the path histories of the connected radio only. Histories of other
|
||||
/// radios are left alone; with no radio scope set, everything is cleared.
|
||||
Future<void> clearAllPathHistories() async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final keys = prefs.getKeys();
|
||||
final pathHistoryKeys = keys.where(
|
||||
(key) => key.startsWith(_pathHistoryPrefix),
|
||||
);
|
||||
final scopedPrefix = _publicKeyHex.isEmpty
|
||||
? _pathHistoryPrefix
|
||||
: '$_pathHistoryPrefix${_publicKeyHex}_';
|
||||
// Pre-scoping keys (no radio prefix) would otherwise be migrated into this
|
||||
// radio on the next load and bring the cleared routes back.
|
||||
final clearLegacy =
|
||||
_publicKeyHex.isNotEmpty && canMigrateLegacyKeys(_publicKeyHex);
|
||||
final pathHistoryKeys = prefs.getKeys().where((key) {
|
||||
if (key.startsWith(scopedPrefix)) return true;
|
||||
return clearLegacy &&
|
||||
key.startsWith(_pathHistoryPrefix) &&
|
||||
!key.substring(_pathHistoryPrefix.length).contains('_');
|
||||
}).toList();
|
||||
|
||||
for (final key in pathHistoryKeys) {
|
||||
await prefs.remove(key);
|
||||
|
||||
@@ -64,6 +64,7 @@ class TcpTransportService {
|
||||
return;
|
||||
}
|
||||
socket.setOption(SocketOption.tcpNoDelay, true);
|
||||
_enableKeepAlive(socket);
|
||||
_socket = socket;
|
||||
_activeHost = trimmedHost;
|
||||
_activePort = port;
|
||||
@@ -139,6 +140,85 @@ class TcpTransportService {
|
||||
unawaited(disconnect().whenComplete(_closeFrameController));
|
||||
}
|
||||
|
||||
/// Seconds of silence before the first keepalive probe, the gap between
|
||||
/// probes, and how many unanswered probes drop the socket: a dead peer or
|
||||
/// a link killed by Wi-Fi power saving surfaces in about a minute instead
|
||||
/// of the OS default of two hours, so the connector can reconnect.
|
||||
static const int _keepAliveIdleSeconds = 30;
|
||||
static const int _keepAliveIntervalSeconds = 10;
|
||||
static const int _keepAliveProbeCount = 3;
|
||||
|
||||
/// Dart's [Socket] has no keepalive option, so the raw socket options are
|
||||
/// set per platform. Every option is best-effort: a platform that rejects
|
||||
/// one keeps a working (if slower to notice a dead peer) connection.
|
||||
void _enableKeepAlive(Socket socket) {
|
||||
final int soKeepAlive;
|
||||
final int? tcpKeepIdle;
|
||||
final int? tcpKeepInterval;
|
||||
final int? tcpKeepCount;
|
||||
if (Platform.isLinux || Platform.isAndroid) {
|
||||
soKeepAlive = 9;
|
||||
tcpKeepIdle = 4;
|
||||
tcpKeepInterval = 5;
|
||||
tcpKeepCount = 6;
|
||||
} else if (Platform.isMacOS || Platform.isIOS) {
|
||||
soKeepAlive = 0x0008;
|
||||
tcpKeepIdle = 0x10; // TCP_KEEPALIVE
|
||||
tcpKeepInterval = 0x101;
|
||||
tcpKeepCount = 0x102;
|
||||
} else if (Platform.isWindows) {
|
||||
soKeepAlive = 0x0008;
|
||||
tcpKeepIdle = null;
|
||||
tcpKeepInterval = null;
|
||||
tcpKeepCount = null;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
void trySet(String name, RawSocketOption option) {
|
||||
try {
|
||||
socket.setRawOption(option);
|
||||
} catch (error) {
|
||||
_debugLogService?.warn('TCP $name not set: $error', tag: 'TCP');
|
||||
}
|
||||
}
|
||||
|
||||
trySet(
|
||||
'SO_KEEPALIVE',
|
||||
RawSocketOption.fromBool(RawSocketOption.levelSocket, soKeepAlive, true),
|
||||
);
|
||||
if (tcpKeepIdle != null) {
|
||||
trySet(
|
||||
'keepalive idle',
|
||||
RawSocketOption.fromInt(
|
||||
RawSocketOption.levelTcp,
|
||||
tcpKeepIdle,
|
||||
_keepAliveIdleSeconds,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (tcpKeepInterval != null) {
|
||||
trySet(
|
||||
'keepalive interval',
|
||||
RawSocketOption.fromInt(
|
||||
RawSocketOption.levelTcp,
|
||||
tcpKeepInterval,
|
||||
_keepAliveIntervalSeconds,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (tcpKeepCount != null) {
|
||||
trySet(
|
||||
'keepalive count',
|
||||
RawSocketOption.fromInt(
|
||||
RawSocketOption.levelTcp,
|
||||
tcpKeepCount,
|
||||
_keepAliveProbeCount,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _cleanupFailedConnect() async {
|
||||
final subscription = _socketSubscription;
|
||||
_socketSubscription = null;
|
||||
|
||||
@@ -36,6 +36,10 @@ class TimeoutPredictionService extends ChangeNotifier {
|
||||
final Map<String, _ContactStats> _contactStats = {};
|
||||
Timer? _persistTimer;
|
||||
|
||||
/// When true, [recordObservation] ignores new deliveries. Review mode sets
|
||||
/// this so the simulated radio's fixed ACK delay never trains the real model.
|
||||
static bool recordingSuspended = false;
|
||||
|
||||
TimeoutPredictionService(StorageService storage) : _storage = storage;
|
||||
TimeoutPredictionService.noStorage() : _storage = null;
|
||||
|
||||
@@ -63,6 +67,7 @@ class TimeoutPredictionService extends ChangeNotifier {
|
||||
required int tripTimeMs,
|
||||
int secondsSinceLastRx = 0,
|
||||
}) {
|
||||
if (recordingSuspended) return;
|
||||
final isFlood = pathLength < 0;
|
||||
final observation = DeliveryObservation(
|
||||
contactKey: contactKey,
|
||||
|
||||
@@ -3,7 +3,11 @@ import 'dart:typed_data';
|
||||
const int usbSerialTxFrameStart = 0x3c;
|
||||
const int usbSerialRxFrameStart = 0x3e;
|
||||
const int usbSerialHeaderLength = 3;
|
||||
// Outgoing (app → radio) payload cap; matches the app's TX frame budget.
|
||||
const int usbSerialMaxPayloadLength = 172;
|
||||
// Incoming (radio → app) payload cap; firmware MAX_FRAME_SIZE is 176 (it
|
||||
// grew by 4 bytes for region transport codes).
|
||||
const int usbSerialMaxRxPayloadLength = 176;
|
||||
|
||||
Uint8List wrapUsbSerialTxFrame(Uint8List payload) {
|
||||
if (payload.length > usbSerialMaxPayloadLength) {
|
||||
@@ -72,7 +76,7 @@ class UsbSerialFrameDecoder {
|
||||
|
||||
final payloadLength =
|
||||
_rxBuffer[_startIndex + 1] | (_rxBuffer[_startIndex + 2] << 8);
|
||||
if (payloadLength > usbSerialMaxPayloadLength) {
|
||||
if (payloadLength > usbSerialMaxRxPayloadLength) {
|
||||
_startIndex++;
|
||||
_compactBufferIfNeeded();
|
||||
continue;
|
||||
|
||||
@@ -86,6 +86,10 @@ class UsbSerialService {
|
||||
if (!_isSupported) {
|
||||
throw UnsupportedError('Web Serial is not supported by this browser.');
|
||||
}
|
||||
if (_port != null || _reader != null || _writer != null) {
|
||||
// Leftovers from a link that died on a read error.
|
||||
await disconnect();
|
||||
}
|
||||
|
||||
_status = UsbSerialStatus.connecting;
|
||||
_lastError = null;
|
||||
@@ -169,7 +173,15 @@ class UsbSerialService {
|
||||
}
|
||||
|
||||
Future<void> disconnect() async {
|
||||
if (_status == UsbSerialStatus.disconnected) return;
|
||||
// A read error or end of stream marks the link disconnected without
|
||||
// closing the port, so still tear down anything left open; otherwise the
|
||||
// next connect() fails with "port already open".
|
||||
if (_status == UsbSerialStatus.disconnected &&
|
||||
_port == null &&
|
||||
_reader == null &&
|
||||
_writer == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final portLabel = _connectedPortName ?? _connectedPortKey;
|
||||
_debugLogService?.info(
|
||||
|
||||
Reference in new issue
Block a user