Tester feedback: routing, bulk select, notifications, map crash

Routing
- Auto routing picks routes by Thompson sampling over faded delivery
  stats (24 h half-life, capped evidence), weighted by what the radio
  currently hears; retries prefer a different route; last attempt floods.
- Route failures are held until a message's fate is known, so an offline
  contact no longer wrecks its route history; failing routes are only
  deleted after a week without a delivery.
- Direct (zero-hop) path is a rotation candidate (#643) and a new Direct
  mode in the routing sheet; history routes are used for repeater logins.
- Remove the route-weight sliders the new chooser no longer uses.

Chats
- Bulk selection in channel chats (spam / not spam / delete / copy) and
  in the Filtered messages list.
- Tapping a search result jumps to the message.
- Swipe-to-reply ignores vertical scrolls.
- Active conversation follows route lifecycle, so covered chats count
  unread again.

Notifications
- Tapping a notification opens its conversation.
- Per-conversation coalescing and one alert per queued-message sync.
- Monochrome status-bar icon; background service stops when the app is
  swiped away; stale notifications cleared on radio or slot change.

Other
- Online map: opaque links and painted dots for dense areas to avoid an
  Impeller GPU crash; expandable hop list on path maps.
- Contact share: clipboard import of shared contacts, "Add again".
- Android: enableEdgeToEdge and scrolling-screenshot support.
- Translations for all new strings; fix mistranslated routing labels.
This commit is contained in:
zjs81 committed 2026-11-08 23:19:15 -07:00
1 parent f81f2686a7
commit 5ea44d6ce9
85 files changed
+6520 -1716

No files matched your search

+8
View File
@@ -33,6 +33,11 @@ class BackgroundService {
eventAction: ForegroundTaskEventAction.repeat(5000),
autoRunOnBoot: false,
allowWifiLock: false,
// The radio link lives in the app process; once the user swipes the
// app away it is gone, so a lingering "connected" notification (or
// an automatic restart) would only be misleading.
allowAutoRestart: false,
stopWithTask: true,
),
);
_initialized = true;
@@ -49,6 +54,9 @@ class BackgroundService {
await FlutterForegroundTask.startService(
notificationTitle: l10n.background_serviceTitle,
notificationText: l10n.background_serviceText,
notificationIcon: const NotificationIcon(
metaDataName: 'org.meshcore.open.NOTIFICATION_ICON',
),
callback: startCallback,
);
}
@@ -281,12 +281,28 @@ class MessageFilterService extends ChangeNotifier {
}
/// User tapped "Spam": store the example and retrain.
Future<void> markSpam({required String sender, required String text}) async {
final key = MessageFilterText.normalize(text);
if (key.isEmpty) return;
_recentClean.removeWhere((e) => MessageFilterText.normalize(e.text) == key);
_hamExamples.removeWhere((e) => MessageFilterText.normalize(e.text) == key);
_addExample(_spamExamples, _example(sender, text), maxSpamExamples);
Future<void> markSpam({required String sender, required String text}) =>
markSpamMany([(sender: sender, text: text)]);
/// Marks several messages as spam with one save and one retrain (bulk
/// selection in a chat).
Future<void> markSpamMany(
List<({String sender, String text})> messages,
) async {
var changed = false;
for (final m in messages) {
final key = MessageFilterText.normalize(m.text);
if (key.isEmpty) continue;
_recentClean.removeWhere(
(e) => MessageFilterText.normalize(e.text) == key,
);
_hamExamples.removeWhere(
(e) => MessageFilterText.normalize(e.text) == key,
);
_addExample(_spamExamples, _example(m.sender, m.text), maxSpamExamples);
changed = true;
}
if (!changed) return;
final training = _retrain();
_notify();
await _guardSave(() async {
@@ -303,17 +319,27 @@ class MessageFilterService extends ChangeNotifier {
required String channelId,
required String sender,
required String text,
}) async {
_tracker.allow(channelId, text);
final key = MessageFilterText.normalize(text);
if (key.isEmpty) {
}) => markNotSpamMany([(channelId: channelId, sender: sender, text: text)]);
/// Marks several messages as not spam with one save and one retrain.
Future<void> markNotSpamMany(
List<({String channelId, String sender, String text})> messages,
) async {
var changed = false;
for (final m in messages) {
_tracker.allow(m.channelId, m.text);
final key = MessageFilterText.normalize(m.text);
if (key.isEmpty) continue;
_spamExamples.removeWhere(
(e) => MessageFilterText.normalize(e.text) == key,
);
_addExample(_hamExamples, _example(m.sender, m.text), maxNotSpamExamples);
changed = true;
}
if (!changed) {
_notify();
return;
}
_spamExamples.removeWhere(
(e) => MessageFilterText.normalize(e.text) == key,
);
_addExample(_hamExamples, _example(sender, text), maxNotSpamExamples);
final training = _retrain();
_notify();
await _guardSave(() async {
+44 -14
View File
@@ -95,6 +95,14 @@ class MessageRetryService extends ChangeNotifier {
final Map<String, Message> _pendingMessages = {};
final Map<String, Contact> _pendingContacts = {};
final Map<String, List<PathSelection>> _attemptPathHistory = {};
/// Route failures of each pending message, held back until its fate is
/// known: if any attempt is acknowledged the contact was reachable and the
/// routes that timed out really failed; if nothing ever gets through the
/// contact was probably just offline, and blaming its routes would wreck a
/// good history.
final Map<String, List<({int attempt, PathSelection selection})>>
_deferredRouteFailures = {};
final Map<String, List<AckHashMapping>> _ackHashToMessageId = {};
final Map<String, List<int>> _expectedAckHashes = {};
final List<_AckHistoryEntry> _ackHistory = [];
@@ -618,6 +626,7 @@ class MessageRetryService extends ChangeNotifier {
_pendingMessages.remove(messageId);
_pendingContacts.remove(messageId);
_attemptPathHistory.remove(messageId);
_deferredRouteFailures.remove(messageId);
_timeoutTimers.remove(messageId);
_resolvedMessages.remove(messageId);
// Cancellation (and other cleanup paths) must release the active in-flight
@@ -653,13 +662,10 @@ class MessageRetryService extends ChangeNotifier {
final backoffMs = 1000 * (1 << message.retryCount);
if (selection != null) {
_recordPathResultFromMessage(
contact.publicKeyHex,
message,
selection,
false,
null,
);
_deferredRouteFailures.putIfAbsent(messageId, () => []).add((
attempt: message.retryCount,
selection: selection,
));
}
final updatedMessage = message.copyWith(
@@ -690,13 +696,19 @@ class MessageRetryService extends ChangeNotifier {
config!.clearContactPath!(contact);
}
_recordPathResultFromMessage(
contact.publicKeyHex,
message,
selection,
false,
null,
);
// Nothing got through on any route: treat the contact as unreachable
// and leave its routes' records alone. Only flood stats count the miss.
// The held failures stay until the grace-period cleanup below, so a
// late ACK still blames the routes that really failed.
if (selection != null && selection.useFlood) {
_recordPathResultFromMessage(
contact.publicKeyHex,
message,
selection,
false,
null,
);
}
config?.updateMessage(failedMessage);
@@ -828,12 +840,29 @@ class MessageRetryService extends ChangeNotifier {
);
final wasAlreadyResolved = _resolvedMessages.contains(matchedMessageId);
final deferredFailures =
_deferredRouteFailures.remove(matchedMessageId) ?? const [];
_cleanupMessage(matchedMessageId);
config?.updateMessage(deliveredMessage);
if (contact != null) {
// The contact was reachable, so earlier attempts that timed out
// really failed — except the attempt this (possibly late) ACK is for.
// Without knowing which attempt was acknowledged, blame nothing.
if (!ambiguousPath && matchedAttemptIndex != null) {
for (final failure in deferredFailures) {
if (failure.attempt == ackedAttempt) continue;
_recordPathResultFromMessage(
contact.publicKeyHex,
message,
failure.selection,
false,
null,
);
}
}
if (!ambiguousPath) {
_recordPathResultFromMessage(
contact.publicKeyHex,
@@ -948,6 +977,7 @@ class MessageRetryService extends ChangeNotifier {
_pendingMessages.clear();
_pendingContacts.clear();
_attemptPathHistory.clear();
_deferredRouteFailures.clear();
_expectedAckHashes.clear();
_ackHistory.clear();
_ackHashToMessageId.clear();
+78
View File
@@ -0,0 +1,78 @@
import 'package:flutter/material.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../screens/channel_chat_screen.dart';
import '../screens/chat_screen.dart';
import 'notification_service.dart';
/// Opens the conversation behind a tapped message notification instead of
/// leaving the user on whatever screen they last had open.
///
/// Only acts while a radio is connected: chats need its contacts/channels, and
/// a cold start goes through the scanner anyway, so a stale tap is dropped.
class NotificationNavigator {
final GlobalKey<NavigatorState> navigatorKey;
final MeshCoreConnector connector;
final NotificationService notifications;
NotificationNavigator({
required this.navigatorKey,
required this.connector,
required this.notifications,
});
void attach() {
notifications.pendingTap.addListener(_handleTap);
_handleTap();
}
void dispose() {
notifications.pendingTap.removeListener(_handleTap);
}
void _handleTap() {
final payload = notifications.pendingTap.value;
if (payload == null) return;
notifications.pendingTap.value = null;
final navigator = navigatorKey.currentState;
if (navigator == null || !connector.isConnected) return;
final sep = payload.indexOf(':');
if (sep <= 0) return;
final kind = payload.substring(0, sep);
final value = payload.substring(sep + 1);
if (kind == 'message') {
if (connector.activeContactKey == value) return;
final contact = connector.getContactByPubKeyHex(value);
if (contact == null ||
(contact.type != advTypeChat && contact.type != advTypeRoom)) {
return;
}
final unread = connector.getUnreadCountForContactKey(value);
connector.markContactRead(value);
navigator.push(
MaterialPageRoute(
builder: (_) =>
ChatScreen(contact: contact, initialUnreadCount: unread),
),
);
} else if (kind == 'channel') {
final index = int.tryParse(value);
if (index == null || connector.activeChannelIndex == index) return;
final channel = connector.channels
.where((c) => c.index == index)
.firstOrNull;
if (channel == null) return;
final unread = connector.getUnreadCountForChannelIndex(index);
connector.markChannelRead(index);
navigator.push(
MaterialPageRoute(
builder: (_) =>
ChannelChatScreen(channel: channel, initialUnreadCount: unread),
),
);
}
}
}
+4 -2
View File
@@ -153,7 +153,9 @@ Future<void> notificationActionBackgroundHandler(
final plugin = FlutterLocalNotificationsPlugin();
await plugin.initialize(
settings: const InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
android: AndroidInitializationSettings(
'@drawable/ic_stat_notification',
),
),
);
final l10n = await _backgroundLocalizations();
@@ -168,7 +170,7 @@ Future<void> notificationActionBackgroundHandler(
channelDescription: 'New message notifications',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
),
),
);
+165 -15
View File
@@ -92,6 +92,42 @@ class NotificationService {
static const _minNotificationInterval = Duration(seconds: 3);
static const _batchWindow = Duration(seconds: 5);
/// Messages for the same conversation that arrive within this window are
/// posted as one notification update. A queue sync can deliver hundreds of
/// messages in seconds; posting each one floods the shade and makes the
/// phone sluggish (Android also drops updates past its rate limit).
static const _coalesceDelay = Duration(milliseconds: 800);
/// While the radio's offline queue is syncing, sound/vibrate at most this
/// often instead of every [_minNotificationInterval].
static const _bulkSyncAlertInterval = Duration(seconds: 60);
/// Reports whether the connector is draining the radio's message queue.
bool Function()? isBulkSyncActive;
/// Current unread total for the app badge. Coalesced conversation updates
/// flush on independent timers, so a count captured when a message was
/// queued can be older than one already posted by another conversation.
int Function()? unreadTotalProvider;
/// Newest badge count seen on any queued message, when no provider is set.
int? _latestQueuedBadgeCount;
final Map<String, List<_PendingNotification>> _pendingConversationUpdates =
{};
final Map<String, Timer> _conversationUpdateTimers = {};
/// Bumped whenever a conversation notification is cleared, so a post still
/// awaiting permission/image lookup does not bring a read chat back.
final Map<int, int> _clearGenerations = {};
int _cancelAllGeneration = 0;
(int, int) _clearGenerationOf(int id) =>
(_cancelAllGeneration, _clearGenerations[id] ?? 0);
void _bumpClearGeneration(int id) =>
_clearGenerations[id] = (_clearGenerations[id] ?? 0) + 1;
DateTime? _lastNotificationTime;
final List<_PendingNotification> _pendingNotifications = [];
bool _isBatchingActive = false;
@@ -102,6 +138,7 @@ class NotificationService {
_suppressNotifications = suppress;
if (suppress) {
_pendingNotifications.clear();
_dropAllPendingConversationUpdates();
}
}
@@ -109,7 +146,7 @@ class NotificationService {
if (_isInitialized) return;
const androidSettings = AndroidInitializationSettings(
'@mipmap/ic_launcher',
'@drawable/ic_stat_notification',
);
const iosSettings = DarwinInitializationSettings(
requestAlertPermission: true,
@@ -395,7 +432,7 @@ class NotificationService {
: 'New message notifications',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
number: badgeCount,
silent: silent,
category: AndroidNotificationCategory.message,
@@ -427,13 +464,22 @@ class NotificationService {
String? senderName,
int? badgeCount,
bool silent = false,
List<_PendingNotification> earlier = const [],
}) async {
final generation = _clearGenerationOf(id);
if (!await _ensureCanNotify()) return;
// Only the newest messages fit in the notification anyway.
final skipped = earlier.length > _maxConversationMessages
? earlier.length - _maxConversationMessages
: 0;
final history = earlier.skip(skipped);
final imagePath = await _resolveNotificationImagePath(
message,
urlImagesEnabled: urlImagesEnabled,
);
if (_clearGenerationOf(id) != generation) return;
final preview = formatNotificationText(message.trim(), _l10n);
final body = preview.isEmpty
? _l10n.notification_receivedNewMessage
@@ -451,6 +497,23 @@ class NotificationService {
..title = title
..badgeCount = badgeCount
..imagePath = imagePath;
for (final prior in history) {
final priorPreview = formatNotificationText(prior.body.trim(), _l10n);
final priorSender = isChannel ? (prior.senderName ?? title) : title;
conversation.add(
Message(
priorPreview.isEmpty
? _l10n.notification_receivedNewMessage
: priorPreview,
DateTime.now(),
Person(
key: isChannel ? 'sender:$priorSender' : payload,
name: priorSender,
),
),
_maxConversationMessages,
);
}
final sender = isChannel ? (senderName ?? title) : title;
conversation.add(
Message(
@@ -556,7 +619,7 @@ class NotificationService {
channelDescription: 'New message notifications',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
),
),
payload: conversation?.payload,
@@ -599,7 +662,7 @@ class NotificationService {
channelDescription: 'New node advertisement notifications',
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
);
const iosDetails = DarwinNotificationDetails(
@@ -655,7 +718,7 @@ class NotificationService {
channelDescription: 'Low battery alerts for the connected device',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
);
const darwinDetails = DarwinNotificationDetails(
@@ -698,16 +761,48 @@ class NotificationService {
}
}
/// Payload (`message:<key>` or `channel:<index>`) of the last tapped
/// conversation notification, until [NotificationNavigator] consumes it.
final ValueNotifier<String?> pendingTap = ValueNotifier<String?>(null);
void _onNotificationTapped(NotificationResponse response) {
final payload = response.payload;
if (payload != null) {
debugPrint('Notification tapped: $payload');
// Handle navigation based on payload
// This can be extended to navigate to specific screens
// Action buttons (reply, mark read, mute) are handled elsewhere; only a
// tap on the notification body should open the conversation. Use the
// response type, not actionId: the Windows plugin fills actionId with the
// payload even for plain body clicks.
if (payload == null ||
response.notificationResponseType !=
NotificationResponseType.selectedNotification) {
return;
}
debugPrint('Notification tapped: $payload');
if (payload.startsWith('message:') || payload.startsWith('channel:')) {
pendingTap.value = payload;
}
}
static const String _radioKeyPrefsKey = 'notifications_radio_key';
/// Called when a radio connects. Notifications name conversations by
/// contact key and channel *slot*; after switching radios a leftover
/// channel notification would open (and mark read) whatever channel the
/// new radio keeps in that slot, so a different radio clears them all.
/// The key is persisted so this also holds across app restarts.
Future<void> bindRadio(String radioKeyHex) async {
String? previous;
try {
previous = PrefsManager.instance.getString(_radioKeyPrefsKey);
await PrefsManager.instance.setString(_radioKeyPrefsKey, radioKeyHex);
} catch (_) {}
if (previous == null || previous == radioKeyHex) return;
if (!await _ensureInitialized()) return;
await cancelAll();
}
Future<void> cancelAll() async {
_cancelAllGeneration++;
_dropAllPendingConversationUpdates();
_conversations.clear();
await _notifications.cancelAll();
await _updateBadge(0);
@@ -722,6 +817,8 @@ class NotificationService {
String contactId,
int totalUnreadCount,
) async {
_dropPendingConversationUpdate(_NotificationType.message, contactId);
_bumpClearGeneration(contactId.hashCode);
if (!await _ensureInitialized()) return;
_conversations.remove(contactId.hashCode);
await _notifications.cancel(id: contactId.hashCode);
@@ -733,6 +830,11 @@ class NotificationService {
int channelIndex,
int totalUnreadCount,
) async {
_dropPendingConversationUpdate(
_NotificationType.channelMessage,
channelIndex.toString(),
);
_bumpClearGeneration(channelIndex.hashCode);
if (!await _ensureInitialized()) return;
_conversations.remove(channelIndex.hashCode);
await _notifications.cancel(id: channelIndex.hashCode);
@@ -860,10 +962,16 @@ class NotificationService {
now.difference(_lastNotificationTime!) < _minNotificationInterval;
// Messages always update their conversation notification so the reply
// action stays available; during a burst they update silently.
// action stays available; bursts are coalesced and update silently.
if (notification.type != _NotificationType.advert) {
_showNotificationImmediately(notification, silent: throttled);
if (!throttled) _lastNotificationTime = now;
_latestQueuedBadgeCount =
notification.badgeCount ?? _latestQueuedBadgeCount;
final key = _conversationKey(notification.type, notification.id);
(_pendingConversationUpdates[key] ??= []).add(notification);
_conversationUpdateTimers[key] ??= Timer(
_coalesceDelay,
() => unawaited(_flushConversationUpdate(key)),
);
return;
}
@@ -890,6 +998,43 @@ class NotificationService {
_lastNotificationTime = now;
}
static String _conversationKey(_NotificationType type, String? id) =>
'${type.name}:$id';
void _dropPendingConversationUpdate(_NotificationType type, String id) {
final key = _conversationKey(type, id);
_conversationUpdateTimers.remove(key)?.cancel();
_pendingConversationUpdates.remove(key);
}
void _dropAllPendingConversationUpdates() {
for (final timer in _conversationUpdateTimers.values) {
timer.cancel();
}
_conversationUpdateTimers.clear();
_pendingConversationUpdates.clear();
}
Future<void> _flushConversationUpdate(String key) async {
_conversationUpdateTimers.remove(key);
final batch = _pendingConversationUpdates.remove(key);
if (batch == null || batch.isEmpty) return;
final now = DateTime.now();
final alertGap = (isBulkSyncActive?.call() ?? false)
? _bulkSyncAlertInterval
: _minNotificationInterval;
final silent =
_lastNotificationTime != null &&
now.difference(_lastNotificationTime!) < alertGap;
if (!silent) _lastNotificationTime = now;
await _showNotificationImmediately(
batch.last,
silent: silent,
earlier: batch.sublist(0, batch.length - 1),
badgeCount: unreadTotalProvider?.call() ?? _latestQueuedBadgeCount,
);
}
Future<void> _processBatch() async {
_isBatchingActive = false;
@@ -912,7 +1057,10 @@ class NotificationService {
Future<void> _showNotificationImmediately(
_PendingNotification notification, {
bool silent = false,
List<_PendingNotification> earlier = const [],
int? badgeCount,
}) async {
final badge = badgeCount ?? notification.badgeCount;
try {
switch (notification.type) {
case _NotificationType.message:
@@ -923,8 +1071,9 @@ class NotificationService {
isChannel: false,
message: notification.body,
urlImagesEnabled: notification.urlImagesEnabled,
badgeCount: notification.badgeCount,
badgeCount: badge,
silent: silent,
earlier: earlier,
);
break;
case _NotificationType.advert:
@@ -946,8 +1095,9 @@ class NotificationService {
message: notification.body,
senderName: notification.senderName,
urlImagesEnabled: notification.urlImagesEnabled,
badgeCount: notification.badgeCount,
badgeCount: badge,
silent: silent,
earlier: earlier,
);
break;
}
@@ -972,7 +1122,7 @@ class NotificationService {
channelDescription: 'Batched notification summaries',
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
);
const notificationDetails = NotificationDetails(android: androidDetails);
+99 -114
View File
@@ -1,16 +1,17 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import '../models/contact.dart';
import '../models/path_history.dart';
import '../models/path_selection.dart';
import '../utils/coalesced_writes.dart';
import 'route_chooser.dart';
import 'storage_service.dart';
class PathHistoryService extends ChangeNotifier {
final StorageService _storage;
final Map<String, ContactPathHistory> _cache = {};
final Map<String, int> _autoRotationIndex = {};
final Map<String, _FloodStats> _floodStats = {};
final Map<String, Future<void>> _pendingLoads = {};
// A path record lands for most received messages, so saves are batched.
@@ -24,10 +25,22 @@ class PathHistoryService extends ChangeNotifier {
static const int _maxHistoryEntries = 100;
/// A failing route is only deleted once it hasn't delivered for this long.
static const Duration _forgetRouteAfter = Duration(days: 7);
int _version = 0;
int get version => _version;
PathHistoryService(this._storage);
final math.Random _random;
final DateTime Function() _now;
/// [random] and [clock] are for tests: route picks are random by design.
PathHistoryService(
this._storage, {
math.Random? random,
DateTime Function()? clock,
}) : _random = random ?? math.Random(),
_now = clock ?? DateTime.now;
void setDevicePublicKey(String publicKeyHex) {
// Queued saves use the storage key on entry, so they still land under
@@ -36,7 +49,6 @@ class PathHistoryService extends ChangeNotifier {
_storage.setPublicKeyHex = publicKeyHex;
_cache.clear();
_cacheAccessOrder.clear();
_autoRotationIndex.clear();
_floodStats.clear();
_version++;
notifyListeners();
@@ -92,7 +104,8 @@ class PathHistoryService extends ChangeNotifier {
double successIncrement = 0.5,
double maxWeight = 5.0,
}) {
if (pathBytes.isEmpty || hopCount < 0) return;
// A flood answered directly credits the direct (zero-hop) path.
if (hopCount < 0 || (pathBytes.isEmpty && hopCount != 0)) return;
if (!_cache.containsKey(contactPubKeyHex)) {
_ensureLoaded(contactPubKeyHex).then((_) {
if (!_cache.containsKey(contactPubKeyHex)) return;
@@ -111,6 +124,8 @@ class PathHistoryService extends ChangeNotifier {
final existing = _findPathRecord(contactPubKeyHex, pathBytes);
final successCount = (existing?.successCount ?? 0) + 1;
final failureCount = existing?.failureCount ?? 0;
final now = _now();
final faded = addRouteResult(existing, success: true, now: now);
final currentWeight = existing?.routeWeight ?? 1.0;
final newWeight = (currentWeight + successIncrement).clamp(0.0, maxWeight);
@@ -129,7 +144,10 @@ class PathHistoryService extends ChangeNotifier {
successCount: successCount,
failureCount: failureCount,
routeWeight: newWeight,
timestamp: DateTime.now(),
timestamp: now,
recentSuccess: faded.success,
recentFailure: faded.failure,
statsAt: now,
);
}
@@ -176,6 +194,8 @@ class PathHistoryService extends ChangeNotifier {
final existing = _findPathRecord(contactPubKeyHex, selection.pathBytes);
final successCount = (existing?.successCount ?? 0) + (success ? 1 : 0);
final failureCount = (existing?.failureCount ?? 0) + (success ? 0 : 1);
final now = _now();
final faded = addRouteResult(existing, success: success, now: now);
final currentWeight = existing?.routeWeight ?? 1.0;
double newWeight;
@@ -183,7 +203,14 @@ class PathHistoryService extends ChangeNotifier {
newWeight = (currentWeight + successIncrement).clamp(0.0, maxWeight);
} else {
newWeight = currentWeight - failureDecrement;
if (newWeight <= 0 && failureCount >= 3) {
// Faded stats already push a failing route out of use, and a repeater
// that is down for a day comes back; only forget a route that keeps
// failing and hasn't delivered in a week. Route weight is bookkeeping
// only now and plays no part in this.
final lastWorked = existing?.timestamp;
final longDead =
lastWorked == null || now.difference(lastWorked) > _forgetRouteAfter;
if (failureCount >= 3 && longDead) {
removePathRecord(contactPubKeyHex, selection.pathBytes);
return;
}
@@ -200,21 +227,31 @@ class PathHistoryService extends ChangeNotifier {
successCount: successCount,
failureCount: failureCount,
routeWeight: newWeight,
timestamp: success ? DateTime.now() : existing?.timestamp,
timestamp: success ? now : existing?.timestamp,
recentSuccess: faded.success,
recentFailure: faded.failure,
statsAt: now,
);
}
/// Route for one send attempt of a message to [contactPubKeyHex].
///
/// The last attempt always floods. Otherwise a known route is drawn by
/// Thompson sampling over faded delivery stats, weighted by how well it
/// fits [context]; routes used for this message's recent attempts score
/// lower so retries usually try something different.
PathSelection selectPathForAttempt(
String contactPubKeyHex, {
required int attemptIndex,
required int maxRetries,
List<PathSelection> recentSelections = const [],
RouteContext context = RouteContext.unknown,
}) {
if (maxRetries <= 0 || attemptIndex >= maxRetries - 1) {
return const PathSelection(pathBytes: [], hopCount: -1, useFlood: true);
}
final ranked = _getRankedPaths(contactPubKeyHex);
final ranked = _getRankedPaths(contactPubKeyHex, context: context);
if (ranked.isEmpty) {
return const PathSelection(pathBytes: [], hopCount: -1, useFlood: true);
}
@@ -225,20 +262,15 @@ class PathHistoryService extends ChangeNotifier {
.where((selection) => !selection.useFlood)
.map((selection) => selection.pathBytes)
.toList();
final candidates = recentPaths.isEmpty
? ranked
: ranked
.where(
(path) => !recentPaths.any(
(recentPath) => _pathsEqual(path.pathBytes, recentPath),
),
)
.toList();
final selected = candidates.isNotEmpty
? (recentPaths.isEmpty
? _selectRotatedCandidate(contactPubKeyHex, candidates)
: candidates.first)
: ranked.first;
final selected = pickRoute(
ranked,
random: _random,
now: _now(),
context: context,
triedThisMessage: (path) => recentPaths.any(
(recentPath) => _pathsEqual(path.pathBytes, recentPath),
),
);
return PathSelection(
pathBytes: selected.pathBytes,
@@ -247,22 +279,6 @@ class PathHistoryService extends ChangeNotifier {
);
}
PathRecord _selectRotatedCandidate(
String contactPubKeyHex,
List<PathRecord> candidates,
) {
if (candidates.length <= 1) {
_autoRotationIndex[contactPubKeyHex] = 0;
return candidates.first;
}
final currentIndex = _autoRotationIndex[contactPubKeyHex] ?? 0;
final selectedIndex = currentIndex % candidates.length;
_autoRotationIndex[contactPubKeyHex] =
(selectedIndex + 1) % candidates.length;
return candidates[selectedIndex];
}
void _addPathRecord({
required String contactPubKeyHex,
required int hopCount,
@@ -274,6 +290,9 @@ class PathHistoryService extends ChangeNotifier {
double? routeWeight,
double initialWeight = 1.0,
DateTime? timestamp,
double? recentSuccess,
double? recentFailure,
DateTime? statsAt,
}) {
void add() => _addPathRecordInternal(
contactPubKeyHex,
@@ -286,6 +305,9 @@ class PathHistoryService extends ChangeNotifier {
routeWeight,
initialWeight,
timestamp,
recentSuccess: recentSuccess,
recentFailure: recentFailure,
statsAt: statsAt,
);
if (_cache.containsKey(contactPubKeyHex)) {
@@ -324,8 +346,11 @@ class PathHistoryService extends ChangeNotifier {
int failureCount,
double? routeWeight,
double initialWeight,
DateTime? timestamp,
) {
DateTime? timestamp, {
double? recentSuccess,
double? recentFailure,
DateTime? statsAt,
}) {
var history = _cache[contactPubKeyHex];
if (history == null) return;
_version++;
@@ -339,6 +364,12 @@ class PathHistoryService extends ChangeNotifier {
}
wasFloodDiscovery = existing.wasFloodDiscovery || wasFloodDiscovery;
timestamp ??= existing.timestamp;
if (recentSuccess == null) {
// Not a result: keep the faded stats as they were.
recentSuccess = existing.recentSuccess;
recentFailure = existing.recentFailure;
statsAt = existing.statsAt;
}
}
routeWeight ??= existing?.routeWeight ?? initialWeight;
@@ -351,6 +382,10 @@ class PathHistoryService extends ChangeNotifier {
successCount: successCount,
failureCount: failureCount,
routeWeight: routeWeight,
// A brand-new record starts with no faded results.
recentSuccess: recentSuccess ?? 0,
recentFailure: recentFailure ?? 0,
statsAt: statsAt,
);
final updatedPaths = List<PathRecord>.from(history.recentPaths);
@@ -462,7 +497,6 @@ class PathHistoryService extends ChangeNotifier {
Future<void> clearPathHistory(String contactPubKeyHex) async {
_cache.remove(contactPubKeyHex);
_cacheAccessOrder.remove(contactPubKeyHex);
_autoRotationIndex.remove(contactPubKeyHex);
_floodStats.remove(contactPubKeyHex);
_writes.cancel(contactPubKeyHex);
await _storage.clearPathHistory(contactPubKeyHex);
@@ -502,34 +536,32 @@ class PathHistoryService extends ChangeNotifier {
return null;
}
List<PathRecord> _getRankedPaths(String contactPubKeyHex) {
List<PathRecord> _getRankedPaths(
String contactPubKeyHex, {
RouteContext context = RouteContext.unknown,
}) {
final history = _cache[contactPubKeyHex];
if (history == null) return [];
// Records without hop bytes are unusable, except the direct path: zero
// hops has no bytes by definition (issue #643: rotation never tried it).
final ranked = List<PathRecord>.from(history.recentPaths)
..removeWhere((p) => p.pathBytes.isEmpty);
final fastestTripMs = _getFastestKnownTripMs(ranked);
final highestRouteWeight = _getHighestKnownRouteWeight(ranked);
..removeWhere((p) => p.pathBytes.isEmpty && p.hopCount != 0);
final now = _now();
final fastest = fastestTripMs(ranked);
final scores = {
for (final p in ranked)
p: routeExpectedScore(
p,
now: now,
fastestTripMs: fastest,
context: context,
),
};
ranked.sort((a, b) {
final scoreCompare =
_scorePathRecord(
b,
fastestTripMs: fastestTripMs,
highestRouteWeight: highestRouteWeight,
).compareTo(
_scorePathRecord(
a,
fastestTripMs: fastestTripMs,
highestRouteWeight: highestRouteWeight,
),
);
if (scoreCompare != 0) {
return scoreCompare;
}
if (a.routeWeight != b.routeWeight) {
return b.routeWeight.compareTo(a.routeWeight);
}
final scoreCompare = scores[b]!.compareTo(scores[a]!);
if (scoreCompare != 0) return scoreCompare;
final aTrip = a.tripTimeMs == 0 ? 999999 : a.tripTimeMs;
final bTrip = b.tripTimeMs == 0 ? 999999 : b.tripTimeMs;
if (aTrip != bTrip) return aTrip.compareTo(bTrip);
@@ -542,58 +574,13 @@ class PathHistoryService extends ChangeNotifier {
}
PathRecord _lowestScoredPath(List<PathRecord> paths) {
final fastestTripMs = _getFastestKnownTripMs(paths);
final highestRouteWeight = _getHighestKnownRouteWeight(paths);
double score(PathRecord p) => _scorePathRecord(
p,
fastestTripMs: fastestTripMs,
highestRouteWeight: highestRouteWeight,
);
final now = _now();
final fastest = fastestTripMs(paths);
double score(PathRecord p) =>
routeExpectedScore(p, now: now, fastestTripMs: fastest);
return paths.reduce((a, b) => score(b) < score(a) ? b : a);
}
int? _getFastestKnownTripMs(List<PathRecord> paths) {
final knownTrips = paths
.where((path) => path.tripTimeMs > 0)
.map((path) => path.tripTimeMs)
.toList();
if (knownTrips.isEmpty) return null;
return knownTrips.reduce((a, b) => a < b ? a : b);
}
double _getHighestKnownRouteWeight(List<PathRecord> paths) {
if (paths.isEmpty) return 1.0;
final highestWeight = paths
.map((path) => path.routeWeight)
.reduce((a, b) => a > b ? a : b);
return highestWeight <= 0 ? 1.0 : highestWeight;
}
double _scorePathRecord(
PathRecord path, {
required int? fastestTripMs,
required double highestRouteWeight,
}) {
final totalAttempts = path.successCount + path.failureCount;
final reliability = (path.successCount + 1) / (totalAttempts + 2);
final latency = fastestTripMs == null || path.tripTimeMs <= 0
? 0.6
: (fastestTripMs / path.tripTimeMs).clamp(0.0, 1.0);
final freshness = path.timestamp == null
? 0.0
: 1.0 /
(1.0 +
(DateTime.now().difference(path.timestamp!).inMinutes /
60.0 /
24.0));
final routeWeight = (path.routeWeight / highestRouteWeight).clamp(0.0, 1.0);
return (reliability * 0.45) +
(latency * 0.25) +
(freshness * 0.1) +
(routeWeight * 0.2);
}
bool _pathsEqual(List<int> a, List<int> b) {
return listEquals(a, b);
}
@@ -615,7 +602,6 @@ class PathHistoryService extends ChangeNotifier {
while (_cache.length > _maxCachedContacts && _cacheAccessOrder.isNotEmpty) {
final oldest = _cacheAccessOrder.removeAt(0);
_cache.remove(oldest);
_autoRotationIndex.remove(oldest);
_floodStats.remove(oldest);
}
}
@@ -632,7 +618,6 @@ class PathHistoryService extends ChangeNotifier {
void clearAllHistories() {
_cache.clear();
_cacheAccessOrder.clear();
_autoRotationIndex.clear();
_floodStats.clear();
_writes.dispose();
_storage.clearAllPathHistories();
+198
View File
@@ -0,0 +1,198 @@
import 'dart:math' as math;
import '../models/path_history.dart';
import '../models/path_selection.dart';
/// Results lose half their weight every [routeStatsHalfLife], so a route's
/// recent behaviour outweighs what it did weeks ago.
const Duration routeStatsHalfLife = Duration(hours: 24);
/// Most results a route's faded stats hold. Fading is by time, so a route
/// used constantly would otherwise pile up so many successes that it takes
/// dozens of failures to lose its rank after its repeater dies; the cap
/// keeps it to a handful.
const double routeEvidenceCap = 16;
/// Multiplier for a route that fits what the radio hears right now (its
/// first hop, or the contact itself for the direct route, was heard).
const double routeContextFitBonus = 1.15;
/// Multiplier for a route that doesn't fit what the radio hears right now.
/// Soft on purpose: not hearing a repeater is weak evidence it's gone.
const double routeContextMissPenalty = 0.6;
/// Small bonus for the path the radio itself currently holds.
const double routeRadioPathBonus = 1.05;
/// Score multiplier for a route already tried for the same message: retries
/// lean toward something different without wasting the attempt on a route
/// much weaker than the one that just missed.
const double routeRetryRepeatPenalty = 0.5;
/// Share of the score that comes from speed; the rest is delivery odds.
const double _speedShare = 0.15;
/// Fraction of a result's weight left after the time from [since] to [now].
double routeDecayFactor(DateTime? since, DateTime now) {
if (since == null) return 1.0;
final seconds = now.difference(since).inSeconds;
if (seconds <= 0) return 1.0;
return math.pow(0.5, seconds / routeStatsHalfLife.inSeconds).toDouble();
}
/// [record]'s faded delivery and failure counts as of [now].
({double success, double failure}) fadedRouteStats(
PathRecord record,
DateTime now,
) {
final f = routeDecayFactor(record.statsAt, now);
return (success: record.recentSuccess * f, failure: record.recentFailure * f);
}
/// Faded counts after adding one result to [record] (or to a new route when
/// it is null) at [now].
({double success, double failure}) addRouteResult(
PathRecord? record, {
required bool success,
required DateTime now,
}) {
final faded = record == null
? (success: 0.0, failure: 0.0)
: fadedRouteStats(record, now);
var s = faded.success + (success ? 1 : 0);
var f = faded.failure + (success ? 0 : 1);
final total = s + f;
if (total > routeEvidenceCap) {
final scale = routeEvidenceCap / total;
s *= scale;
f *= scale;
}
return (success: s, failure: f);
}
/// How well [record] fits what the radio hears right now.
double routeContextFactor(PathRecord record, RouteContext context) {
var factor = 1.0;
final radioPath = context.radioPath;
if (radioPath != null &&
radioPath.length == record.pathBytes.length &&
_sameBytes(radioPath, record.pathBytes)) {
factor *= routeRadioPathBonus;
}
if (!context.hasNeighbourInfo) return factor;
final fits = record.hopCount == 0
? context.contactHeardDirectly
: context.firstHopHeard(record.pathBytes, record.hashWidth);
return factor * (fits ? routeContextFitBonus : routeContextMissPenalty);
}
double _speedFactor(PathRecord record, int? fastestTripMs) {
final speed = fastestTripMs == null || record.tripTimeMs <= 0
? 0.6
: (fastestTripMs / record.tripTimeMs).clamp(0.0, 1.0);
return (1 - _speedShare) + _speedShare * speed;
}
/// Fastest known trip time among [records], or null when none is known.
int? fastestTripMs(Iterable<PathRecord> records) {
int? best;
for (final r in records) {
if (r.tripTimeMs > 0 && (best == null || r.tripTimeMs < best)) {
best = r.tripTimeMs;
}
}
return best;
}
/// Deterministic rank: expected delivery odds (faded), adjusted for speed
/// and context. Used for ordering lists and choosing what to evict.
double routeExpectedScore(
PathRecord record, {
required DateTime now,
required int? fastestTripMs,
RouteContext context = RouteContext.unknown,
}) {
final stats = fadedRouteStats(record, now);
final mean = (stats.success + 1) / (stats.success + stats.failure + 2);
return mean *
_speedFactor(record, fastestTripMs) *
routeContextFactor(record, context);
}
/// Thompson sampling: draws plausible delivery odds for each route from what
/// is known about it and returns the route with the best draw. Proven routes
/// win most of the time; uncertain ones are still tried now and then, so a
/// route that starts working again gets noticed.
PathRecord pickRoute(
List<PathRecord> candidates, {
required math.Random random,
required DateTime now,
RouteContext context = RouteContext.unknown,
bool Function(PathRecord record)? triedThisMessage,
}) {
assert(candidates.isNotEmpty);
final fastest = fastestTripMs(candidates);
PathRecord? best;
var bestScore = -1.0;
for (final record in candidates) {
final stats = fadedRouteStats(record, now);
final draw = sampleBeta(random, stats.success + 1, stats.failure + 1);
final score =
draw *
_speedFactor(record, fastest) *
routeContextFactor(record, context) *
(triedThisMessage?.call(record) == true
? routeRetryRepeatPenalty
: 1.0);
if (score > bestScore) {
bestScore = score;
best = record;
}
}
return best!;
}
/// A sample from Beta([a], [b]), both > 0.
double sampleBeta(math.Random random, double a, double b) {
final x = _sampleGamma(random, a);
final y = _sampleGamma(random, b);
final sum = x + y;
return sum <= 0 ? 0.5 : x / sum;
}
/// Gamma(shape, 1) by Marsaglia–Tsang; shapes below 1 use the boost
/// Gamma(a) = Gamma(a + 1) * U^(1/a).
double _sampleGamma(math.Random random, double shape) {
if (shape < 1) {
final u = random.nextDouble();
return _sampleGamma(random, shape + 1) * math.pow(u, 1 / shape);
}
final d = shape - 1 / 3;
final c = 1 / math.sqrt(9 * d);
while (true) {
double x;
double v;
do {
x = _sampleNormal(random);
v = 1 + c * x;
} while (v <= 0);
v = v * v * v;
final u = random.nextDouble();
if (u < 1 - 0.0331 * x * x * x * x) return d * v;
if (math.log(u) < 0.5 * x * x + d * (1 - v + math.log(v))) return d * v;
}
}
double _sampleNormal(math.Random random) {
// Box–Muller; 1 - nextDouble() avoids log(0).
final u1 = 1 - random.nextDouble();
final u2 = random.nextDouble();
return math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2);
}
bool _sameBytes(List<int> a, List<int> b) {
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
+153
View File
@@ -0,0 +1,153 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import '../utils/platform_info.dart';
/// Dart half of Android's scrolling screenshot ("Capture more").
///
/// The native `FlutterScrollCapture` asks for the main scrollable on screen,
/// then has it scrolled strip by strip while it copies pixels. All sizes on
/// the channel are physical pixels in the Flutter view.
class ScrollCaptureService {
ScrollCaptureService._();
static const MethodChannel _channel = MethodChannel(
'meshcore_open/scroll_capture',
);
static ScrollableState? _target;
static double _startPixels = 0;
static void initialize() {
if (kIsWeb || !PlatformInfo.isAndroid) return;
_channel.setMethodCallHandler(_handle);
}
static Future<Object?> _handle(MethodCall call) async {
switch (call.method) {
case 'search':
return _search();
case 'start':
_startPixels = _target?.position.pixels ?? 0;
return null;
case 'scroll':
final args = call.arguments as Map<Object?, Object?>;
return _scrollTo((args['top'] as num).toDouble());
case 'end':
final target = _target;
_target = null;
if (target != null && target.mounted) {
target.position.jumpTo(_startPixels);
}
return null;
}
return null;
}
static FlutterView? get _view =>
WidgetsBinding.instance.platformDispatcher.implicitView;
/// The largest vertically scrollable, user-visible list on the top route.
static Map<String, int>? _search() {
final view = _view;
final root = WidgetsBinding.instance.rootElement;
if (view == null || root == null) return null;
final dpr = view.devicePixelRatio;
final screen = Offset.zero & (view.physicalSize / dpr);
ScrollableState? best;
Rect? bestRect;
void visit(Element element) {
if (element is StatefulElement && element.state is ScrollableState) {
final state = element.state as ScrollableState;
final rect = _candidateRect(state, element.renderObject, screen, view);
if (rect != null &&
(bestRect == null ||
rect.width * rect.height >=
bestRect!.width * bestRect!.height)) {
best = state;
bestRect = rect;
}
}
element.visitChildren(visit);
}
root.visitChildren(visit);
final rect = bestRect;
_target = best;
if (best == null || rect == null) return null;
return {
'left': (rect.left * dpr).round(),
'top': (rect.top * dpr).round(),
'right': (rect.right * dpr).round(),
'bottom': (rect.bottom * dpr).round(),
};
}
static Rect? _candidateRect(
ScrollableState state,
RenderObject? renderObject,
Rect screen,
FlutterView view,
) {
if (axisDirectionToAxis(state.axisDirection) != Axis.vertical) return null;
final position = state.position;
if (!position.hasContentDimensions ||
position.maxScrollExtent <= position.minScrollExtent) {
return null;
}
if (renderObject is! RenderBox ||
!renderObject.attached ||
!renderObject.hasSize) {
return null;
}
final rect = MatrixUtils.transformRect(
renderObject.getTransformTo(null),
Offset.zero & renderObject.size,
).intersect(screen);
if (rect.isEmpty || rect.height < 100) return null;
// Only a list the user can actually see: the topmost hit at its centre
// must be inside it (rules out lists on routes underneath, or covered
// by a sheet or dialog).
final result = HitTestResult();
WidgetsBinding.instance.hitTestInView(result, rect.center, view.viewId);
if (!result.path.any((entry) => entry.target == renderObject)) return null;
return rect;
}
/// Scrolls so the strip starting [top] physical px below the start
/// position's top edge is at the top of the list, as far as the content
/// allows. Returns how far it actually moved, in physical px.
static Future<double> _scrollTo(double top) async {
final target = _target;
final view = _view;
if (target == null || !target.mounted || view == null) return 0;
final dpr = view.devicePixelRatio;
final position = target.position;
// In a reversed list (the chat transcript) moving down the screen means
// smaller scroll offsets.
final up = target.axisDirection == AxisDirection.up;
final delta = top / dpr;
final wanted = (up ? _startPixels - delta : _startPixels + delta).clamp(
position.minScrollExtent,
position.maxScrollExtent,
);
position.jumpTo(wanted);
// Bounded: if frames are not being produced (app no longer resumed),
// waiting forever would leave the native capture request hanging.
for (var i = 0; i < 2; i++) {
await WidgetsBinding.instance.endOfFrame.timeout(
const Duration(milliseconds: 250),
onTimeout: () {},
);
}
if (!target.mounted) return 0;
final moved = up
? _startPixels - position.pixels
: position.pixels - _startPixels;
return moved * dpr;
}
}