Compare commits

...

3 Commits

Author SHA1 Message Date
Janez T
e85dccea35 feat: Add location-based DM retries 2026-03-23 15:16:59 +01:00
Janez T
019224d955 fix: Hide public channel and show signal pills #123 2026-03-23 15:04:45 +01:00
Janez T
4c048a5a50 fix: Show recipient activity previews 2026-03-23 10:44:20 +01:00
21 changed files with 1185 additions and 298 deletions

View File

@@ -489,7 +489,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 124;
CURRENT_PROJECT_VERSION = 125;
DEVELOPMENT_TEAM = JND55328G8;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@@ -511,7 +511,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 124;
CURRENT_PROJECT_VERSION = 125;
DEVELOPMENT_TEAM = JND55328G8;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
@@ -530,7 +530,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 124;
CURRENT_PROJECT_VERSION = 125;
DEVELOPMENT_TEAM = JND55328G8;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
@@ -547,7 +547,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 124;
CURRENT_PROJECT_VERSION = 125;
DEVELOPMENT_TEAM = JND55328G8;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
@@ -679,7 +679,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 124;
CURRENT_PROJECT_VERSION = 125;
DEVELOPMENT_TEAM = JND55328G8;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@@ -702,7 +702,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 124;
CURRENT_PROJECT_VERSION = 125;
DEVELOPMENT_TEAM = JND55328G8;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;

View File

@@ -43,7 +43,7 @@
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>124</string>
<string>125</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>ITSAppUsesNonExemptEncryption</key>

View File

@@ -5,22 +5,22 @@
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.00024">
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.000216">
</testcase>
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="1.144858">
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="1.086406">
</testcase>
<testcase classname="fastlane.lanes" name="2: build_app" time="98.142592">
<testcase classname="fastlane.lanes" name="2: build_app" time="96.919368">
</testcase>
<testcase classname="fastlane.lanes" name="3: upload_to_app_store" time="157.12775">
<testcase classname="fastlane.lanes" name="3: upload_to_app_store" time="563.579992">
</testcase>

View File

@@ -9,6 +9,11 @@ class PathRecord {
final int failureCount;
final int lastRoundTripTimeMs;
final DateTime lastUsedAt;
final DateTime? lastSucceededAt;
final double? senderLatitude;
final double? senderLongitude;
final double? recipientLatitude;
final double? recipientLongitude;
const PathRecord({
required this.pathBytes,
@@ -19,6 +24,11 @@ class PathRecord {
required this.failureCount,
required this.lastRoundTripTimeMs,
required this.lastUsedAt,
required this.lastSucceededAt,
required this.senderLatitude,
required this.senderLongitude,
required this.recipientLatitude,
required this.recipientLongitude,
});
String get signature =>
@@ -36,6 +46,11 @@ class PathRecord {
int? failureCount,
int? lastRoundTripTimeMs,
DateTime? lastUsedAt,
DateTime? lastSucceededAt,
double? senderLatitude,
double? senderLongitude,
double? recipientLatitude,
double? recipientLongitude,
}) {
return PathRecord(
pathBytes: pathBytes ?? this.pathBytes,
@@ -46,6 +61,11 @@ class PathRecord {
failureCount: failureCount ?? this.failureCount,
lastRoundTripTimeMs: lastRoundTripTimeMs ?? this.lastRoundTripTimeMs,
lastUsedAt: lastUsedAt ?? this.lastUsedAt,
lastSucceededAt: lastSucceededAt ?? this.lastSucceededAt,
senderLatitude: senderLatitude ?? this.senderLatitude,
senderLongitude: senderLongitude ?? this.senderLongitude,
recipientLatitude: recipientLatitude ?? this.recipientLatitude,
recipientLongitude: recipientLongitude ?? this.recipientLongitude,
);
}
@@ -59,6 +79,11 @@ class PathRecord {
'failure_count': failureCount,
'last_round_trip_time_ms': lastRoundTripTimeMs,
'last_used_at': lastUsedAt.toIso8601String(),
'last_succeeded_at': lastSucceededAt?.toIso8601String(),
'sender_latitude': senderLatitude,
'sender_longitude': senderLongitude,
'recipient_latitude': recipientLatitude,
'recipient_longitude': recipientLongitude,
};
}
@@ -79,6 +104,13 @@ class PathRecord {
lastUsedAt:
DateTime.tryParse(json['last_used_at'] as String? ?? '') ??
DateTime.fromMillisecondsSinceEpoch(0),
lastSucceededAt: DateTime.tryParse(
json['last_succeeded_at'] as String? ?? '',
),
senderLatitude: (json['sender_latitude'] as num?)?.toDouble(),
senderLongitude: (json['sender_longitude'] as num?)?.toDouble(),
recipientLatitude: (json['recipient_latitude'] as num?)?.toDouble(),
recipientLongitude: (json['recipient_longitude'] as num?)?.toDouble(),
);
}
}

View File

@@ -1761,6 +1761,7 @@ class AppProvider with ChangeNotifier {
return _prepareDirectMessageSend(
messageId: messageId,
contact: contact,
retryAttempt: retryAttempt,
);
};
@@ -1830,23 +1831,47 @@ class AppProvider with ChangeNotifier {
Future<Contact> _prepareDirectMessageSend({
required String messageId,
required Contact contact,
required int retryAttempt,
}) async {
final latestContact =
contactsProvider.findContactByKey(contact.publicKey) ?? contact;
var session = _directMessageRouteSessions[messageId];
if (session == null) {
final selection = await _pathHistoryService.getSelectionForContact(
latestContact,
autoRouteRotationEnabled: _autoRouteRotationEnabled,
);
final selection = latestContact.routeHasPath && latestContact.routeHopCount > 0
? PathSelection(
mode: PathSelectionMode.directCurrent,
pathBytes: Uint8List.fromList(latestContact.routePathBytes),
hopCount: latestContact.routeHopCount,
hashSize: latestContact.routeHashSize,
)
: await _pathHistoryService.getSelectionForContact(
latestContact,
autoRouteRotationEnabled: _autoRouteRotationEnabled,
);
session = _DirectMessageRouteSession(
currentSelection: selection,
originalRoute: ContactRouteCodec.fromContact(latestContact),
routerFallbackAttempted: false,
);
_directMessageRouteSessions[messageId] = session;
}
if (!session.routerFallbackAttempted) {
final currentSignature =
latestContact.routeHasPath && latestContact.routeHopCount > 0
? latestContact.routePathBytes
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
.join()
: null;
final selection = await _resolveDirectMessageSelectionForRetry(
latestContact,
retryAttempt: retryAttempt,
currentSignature: currentSignature,
fallbackSelection: session.currentSelection,
);
session = session.copyWith(currentSelection: selection);
}
_directMessageRouteSessions[messageId] = session;
await _applyPathSelection(
latestContact,
session.currentSelection,
@@ -1857,6 +1882,43 @@ class AppProvider with ChangeNotifier {
latestContact;
}
Future<PathSelection> _resolveDirectMessageSelectionForRetry(
Contact contact, {
required int retryAttempt,
required String? currentSignature,
required PathSelection fallbackSelection,
}) async {
if (contact.routeHasPath && contact.routeHopCount > 0 && retryAttempt <= 1) {
return PathSelection(
mode: PathSelectionMode.directCurrent,
pathBytes: Uint8List.fromList(contact.routePathBytes),
hopCount: contact.routeHopCount,
hashSize: contact.routeHashSize,
);
}
if (retryAttempt == 2) {
return PathSelection.flood();
}
if (retryAttempt >= 3) {
final historicalSelection = await _pathHistoryService
.getLastSuccessfulDirectSelection(
contact,
excludeSignature: currentSignature,
senderLatitude: locationTrackingService.currentPosition?.latitude,
senderLongitude: locationTrackingService.currentPosition?.longitude,
recipientLatitude: contact.displayLocation?.latitude,
recipientLongitude: contact.displayLocation?.longitude,
);
if (historicalSelection != null) {
return historicalSelection;
}
}
return fallbackSelection;
}
Future<void> _applyPathSelection(
Contact contact,
PathSelection selection, {
@@ -2031,6 +2093,10 @@ class AppProvider with ChangeNotifier {
session.currentSelection,
success: true,
roundTripTimeMs: roundTripTimeMs,
senderLatitude: locationTrackingService.currentPosition?.latitude,
senderLongitude: locationTrackingService.currentPosition?.longitude,
recipientLatitude: contact.displayLocation?.latitude,
recipientLongitude: contact.displayLocation?.longitude,
),
);
}

View File

@@ -21,8 +21,8 @@ class MessageRetryManager {
final Map<String, int> _pathFailureStreaks = {};
/// Max retry attempts when the contact has a known path.
/// Official MeshCore app uses 5 (with auto-retry) or 3 (without).
static const int maxRetryAttemptsWithPath = 5;
/// Sequence: 2 direct attempts, flood, then last successful route.
static const int maxRetryAttemptsWithPath = 3;
/// No retries for flood-only contacts (no known path).
/// Value 0 means: don't retry at all, go straight to fallback/fail.

View File

@@ -2354,17 +2354,6 @@ class MessagesProvider with ChangeNotifier {
return;
}
// On the last attempt, reset the path to force flood mode
// (matches official MeshCore app behaviour)
if (_retryManager.isLastAttempt(currentMessage, contact)) {
debugPrint(
'🔄 [MessagesProvider] Last attempt — resetting path to flood for $messageId',
);
if (resetPathBeforeLastRetryCallback != null) {
await resetPathBeforeLastRetryCallback!(contact);
}
}
if (sendMessageCallback != null) {
final queued = await sendMessageCallback!(
contactPublicKey: contact.publicKey,

View File

@@ -19,6 +19,8 @@ import '../utils/avatar_label_helper.dart';
import '../widgets/common/contact_avatar.dart';
import '../widgets/contacts/contact_tile.dart';
import '../widgets/contacts/add_channel_dialog.dart';
import '../services/region_scope_preferences.dart';
import '../utils/toast_logger.dart';
import 'add_contact_screen.dart';
class ContactsTab extends StatefulWidget {
@@ -546,6 +548,15 @@ class _ContactsTabState extends State<ContactsTab> {
await _exportHashChannelPskBase64(context, channel);
},
),
_ChannelSheetAction(
icon: Icons.language_rounded,
label: l10n.setRegionScope,
onTap: () async {
Navigator.pop(context);
if (!context.mounted) return;
_showRegionScopeForChannel(context, channel);
},
),
if (!channel.isPublicChannel)
_ChannelSheetAction(
icon: Icons.delete_outline_rounded,
@@ -575,6 +586,38 @@ class _ContactsTabState extends State<ContactsTab> {
);
}
void _showRegionScopeForChannel(BuildContext context, Contact channel) async {
final channelIdx = channel.publicKey.length > 1 ? channel.publicKey[1] : 0;
final l10n = AppLocalizations.of(context)!;
final currentScope = await RegionScopePreferences.getScope(channelIdx);
if (!context.mounted) return;
showModalBottomSheet(
context: context,
showDragHandle: true,
isScrollControlled: true,
builder: (sheetContext) {
return _ContactsRegionScopeSheet(
currentScopeName: currentScope?.name,
l10n: l10n,
onScopeSelected: (String? name) async {
Navigator.of(sheetContext).pop();
if (name == null) {
await RegionScopePreferences.clearScope(channelIdx);
if (!context.mounted) return;
ToastLogger.success(context, l10n.regionScopeCleared);
} else {
final key = RegionScopePreferences.deriveRegionKey(name);
await RegionScopePreferences.setScope(channelIdx, name, key);
if (!context.mounted) return;
ToastLogger.success(context, l10n.regionScopeSet(name));
}
},
);
},
);
}
Color _sectionAccentColor(BuildContext context, ContactSection section) {
final colorScheme = Theme.of(context).colorScheme;
switch (section) {
@@ -2394,3 +2437,165 @@ class _MetricChip extends StatelessWidget {
);
}
}
class _ContactsRegionScopeSheet extends StatefulWidget {
final String? currentScopeName;
final AppLocalizations l10n;
final ValueChanged<String?> onScopeSelected;
const _ContactsRegionScopeSheet({
required this.currentScopeName,
required this.l10n,
required this.onScopeSelected,
});
@override
State<_ContactsRegionScopeSheet> createState() =>
_ContactsRegionScopeSheetState();
}
class _ContactsRegionScopeSheetState
extends State<_ContactsRegionScopeSheet> {
final TextEditingController _nameController = TextEditingController();
@override
void dispose() {
_nameController.dispose();
super.dispose();
}
void _submitManualName() {
var name = _nameController.text.trim();
if (name.isEmpty) return;
if (!name.startsWith('#')) name = '#$name';
widget.onScopeSelected(name);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final l10n = widget.l10n;
return SafeArea(
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * 0.72,
),
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 8, 20, 20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.regionScope,
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text(
l10n.regionScopeWarning,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 16),
_ScopeOption(
label: l10n.regionScopeNone,
isSelected: widget.currentScopeName == null,
onTap: () => widget.onScopeSelected(null),
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: TextField(
controller: _nameController,
decoration: InputDecoration(
hintText: l10n.enterRegionName,
isDense: true,
prefixText: '#',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 10,
),
),
onSubmitted: (_) => _submitManualName(),
),
),
const SizedBox(width: 8),
FilledButton.tonal(
onPressed: _submitManualName,
child: const Icon(Icons.check_rounded, size: 20),
),
],
),
],
),
),
),
);
}
}
class _ScopeOption extends StatelessWidget {
final String label;
final bool isSelected;
final VoidCallback onTap;
const _ScopeOption({
required this.label,
required this.isSelected,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Material(
color: isSelected
? colorScheme.primaryContainer
: colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(12),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(
isSelected
? Icons.radio_button_checked_rounded
: Icons.radio_button_off_rounded,
size: 20,
color: isSelected
? colorScheme.primary
: colorScheme.onSurfaceVariant,
),
const SizedBox(width: 12),
Expanded(
child: Text(
label,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
color: isSelected
? colorScheme.onPrimaryContainer
: colorScheme.onSurface,
),
),
),
],
),
),
),
);
}
}

View File

@@ -37,7 +37,6 @@ import '../providers/image_provider.dart' as ip;
import '../services/image_codec_service.dart';
import '../services/image_preferences.dart';
import '../services/region_scope_preferences.dart';
import '../services/region_discovery_service.dart';
import 'package:image_picker/image_picker.dart';
import '../l10n/app_localizations.dart';
@@ -1763,12 +1762,7 @@ class _MessagesTabState extends State<MessagesTab> {
void _showRegionScopeSheet() {
final channelIdx = _selectedRecipient?.publicKey[1] ?? 0;
final contactsProvider = context.read<ContactsProvider>();
final connectionProvider = context.read<ConnectionProvider>();
final l10n = AppLocalizations.of(context)!;
final repeaters = contactsProvider.contacts
.where((c) => c.isRepeater)
.toList();
showModalBottomSheet(
context: context,
@@ -1777,8 +1771,6 @@ class _MessagesTabState extends State<MessagesTab> {
builder: (sheetContext) {
return _RegionScopeSheet(
currentScopeName: _channelRegionScopeName,
repeaters: repeaters,
connectionProvider: connectionProvider,
l10n: l10n,
onScopeSelected: (String? name) async {
Navigator.of(sheetContext).pop();
@@ -2412,15 +2404,11 @@ class _MessagesTabState extends State<MessagesTab> {
/// Bottom sheet for selecting a region scope for the current channel.
class _RegionScopeSheet extends StatefulWidget {
final String? currentScopeName;
final List<Contact> repeaters;
final ConnectionProvider connectionProvider;
final AppLocalizations l10n;
final ValueChanged<String?> onScopeSelected;
const _RegionScopeSheet({
required this.currentScopeName,
required this.repeaters,
required this.connectionProvider,
required this.l10n,
required this.onScopeSelected,
});
@@ -2431,8 +2419,6 @@ class _RegionScopeSheet extends StatefulWidget {
class _RegionScopeSheetState extends State<_RegionScopeSheet> {
final TextEditingController _nameController = TextEditingController();
List<String> _discoveredRegions = [];
bool _isDiscovering = false;
@override
void dispose() {
@@ -2440,30 +2426,6 @@ class _RegionScopeSheetState extends State<_RegionScopeSheet> {
super.dispose();
}
Future<void> _discoverRegions() async {
if (widget.repeaters.isEmpty) return;
setState(() => _isDiscovering = true);
final allRegions = <String>{};
for (final repeater in widget.repeaters) {
final regions = await RegionDiscoveryService.discoverFromRepeater(
repeaterPublicKey: repeater.publicKey,
connectionProvider: widget.connectionProvider,
);
allRegions.addAll(regions);
}
if (!mounted) return;
setState(() {
_discoveredRegions = allRegions.toList()..sort();
_isDiscovering = false;
});
if (_discoveredRegions.isEmpty && mounted) {
ToastLogger.info(context, widget.l10n.noRegionsFound);
}
}
void _submitManualName() {
var name = _nameController.text.trim();
if (name.isEmpty) return;
@@ -2504,7 +2466,6 @@ class _RegionScopeSheetState extends State<_RegionScopeSheet> {
),
const SizedBox(height: 16),
// "None" option
_RegionOptionTile(
label: l10n.regionScopeNone,
isSelected: widget.currentScopeName == null,
@@ -2512,7 +2473,6 @@ class _RegionScopeSheetState extends State<_RegionScopeSheet> {
),
const SizedBox(height: 8),
// Manual entry
Row(
children: [
Expanded(
@@ -2540,38 +2500,6 @@ class _RegionScopeSheetState extends State<_RegionScopeSheet> {
),
],
),
const SizedBox(height: 16),
// Discover button
if (widget.repeaters.isNotEmpty)
FilledButton.tonalIcon(
onPressed: _isDiscovering ? null : _discoverRegions,
icon: _isDiscovering
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.search_rounded, size: 18),
label: Text(
_isDiscovering
? l10n.discoveringRegions
: l10n.discoverRegions,
),
),
// Discovered regions
if (_discoveredRegions.isNotEmpty) ...[
const SizedBox(height: 12),
for (final region in _discoveredRegions) ...[
_RegionOptionTile(
label: region,
isSelected: widget.currentScopeName == region,
onTap: () => widget.onScopeSelected(region),
),
const SizedBox(height: 4),
],
],
],
),
),

View File

@@ -429,6 +429,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
Future<void> _editFastLocationChannel() async {
final channels =
List<Contact>.from(context.read<ContactsProvider>().channels)
..removeWhere((c) => c.isPublicChannel)
..sort((a, b) {
final aIdx = a.publicKey.length > 1 ? a.publicKey[1] : 0;
final bIdx = b.publicKey.length > 1 ? b.publicKey[1] : 0;

View File

@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:geolocator/geolocator.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/contact.dart';
@@ -9,7 +10,7 @@ import '../models/path_selection.dart';
import '../utils/log_rx_route_decoder.dart';
class PathHistoryService {
static const String _storageKey = 'contact_path_history_v1';
static const String _storageKey = 'contact_path_history_v2';
static const int _maxDirectPaths = 20;
static const int _topRotationCount = 3;
@@ -59,6 +60,11 @@ class PathHistoryService {
failureCount: existing?.failureCount ?? 0,
lastRoundTripTimeMs: existing?.lastRoundTripTimeMs ?? 0,
lastUsedAt: DateTime.now(),
lastSucceededAt: existing?.lastSucceededAt,
senderLatitude: existing?.senderLatitude,
senderLongitude: existing?.senderLongitude,
recipientLatitude: existing?.recipientLatitude,
recipientLongitude: existing?.recipientLongitude,
);
await _saveHistory(
@@ -104,6 +110,11 @@ class PathHistoryService {
failureCount: existing?.failureCount ?? 0,
lastRoundTripTimeMs: existing?.lastRoundTripTimeMs ?? 0,
lastUsedAt: DateTime.now(),
lastSucceededAt: existing?.lastSucceededAt,
senderLatitude: existing?.senderLatitude,
senderLongitude: existing?.senderLongitude,
recipientLatitude: existing?.recipientLatitude,
recipientLongitude: existing?.recipientLongitude,
);
await _saveHistory(
@@ -172,6 +183,10 @@ class PathHistoryService {
PathSelection selection, {
required bool success,
int? roundTripTimeMs,
double? senderLatitude,
double? senderLongitude,
double? recipientLatitude,
double? recipientLongitude,
}) async {
await initialize();
final history = _historyFor(contactPublicKeyHex);
@@ -206,6 +221,13 @@ class PathHistoryService {
? (roundTripTimeMs ?? existing?.lastRoundTripTimeMs ?? 0)
: (existing?.lastRoundTripTimeMs ?? 0),
lastUsedAt: DateTime.now(),
lastSucceededAt: success ? DateTime.now() : existing?.lastSucceededAt,
senderLatitude: success ? senderLatitude : existing?.senderLatitude,
senderLongitude: success ? senderLongitude : existing?.senderLongitude,
recipientLatitude:
success ? recipientLatitude : existing?.recipientLatitude,
recipientLongitude:
success ? recipientLongitude : existing?.recipientLongitude,
);
await _saveHistory(
contactPublicKeyHex,
@@ -215,6 +237,54 @@ class PathHistoryService {
);
}
Future<PathSelection?> getLastSuccessfulDirectSelection(
Contact contact, {
String? excludeSignature,
double? senderLatitude,
double? senderLongitude,
double? recipientLatitude,
double? recipientLongitude,
}) async {
await initialize();
final history = _historyFor(contact.publicKeyHex);
final ranked = history.directPaths
.where(
(record) =>
record.successCount > 0 &&
record.lastSucceededAt != null &&
record.signature != excludeSignature,
)
.toList()
..sort((a, b) {
final locationCompare = _compareLocationFit(
a,
b,
senderLatitude: senderLatitude,
senderLongitude: senderLongitude,
recipientLatitude: recipientLatitude,
recipientLongitude: recipientLongitude,
);
if (locationCompare != 0) return locationCompare;
final succeededCompare = b.lastSucceededAt!.compareTo(
a.lastSucceededAt!,
);
if (succeededCompare != 0) return succeededCompare;
return _comparePathRecords(a, b);
});
if (ranked.isEmpty) {
return null;
}
final record = ranked.first;
return PathSelection(
mode: PathSelectionMode.directHistorical,
pathBytes: Uint8List.fromList(record.pathBytes),
hopCount: record.hopCount,
hashSize: record.hashSize,
);
}
ContactPathHistory historyFor(String contactPublicKeyHex) {
return _cache[contactPublicKeyHex] ??
ContactPathHistory.empty(contactPublicKeyHex);
@@ -279,4 +349,68 @@ class PathHistoryService {
String _signature(Uint8List bytes) =>
bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
int _compareLocationFit(
PathRecord a,
PathRecord b, {
required double? senderLatitude,
required double? senderLongitude,
required double? recipientLatitude,
required double? recipientLongitude,
}) {
final aDistance = _locationDistanceScore(
a,
senderLatitude: senderLatitude,
senderLongitude: senderLongitude,
recipientLatitude: recipientLatitude,
recipientLongitude: recipientLongitude,
);
final bDistance = _locationDistanceScore(
b,
senderLatitude: senderLatitude,
senderLongitude: senderLongitude,
recipientLatitude: recipientLatitude,
recipientLongitude: recipientLongitude,
);
return aDistance.compareTo(bDistance);
}
double _locationDistanceScore(
PathRecord record, {
required double? senderLatitude,
required double? senderLongitude,
required double? recipientLatitude,
required double? recipientLongitude,
}) {
var total = 0.0;
var matched = false;
if (senderLatitude != null &&
senderLongitude != null &&
record.senderLatitude != null &&
record.senderLongitude != null) {
matched = true;
total += Geolocator.distanceBetween(
senderLatitude,
senderLongitude,
record.senderLatitude!,
record.senderLongitude!,
);
}
if (recipientLatitude != null &&
recipientLongitude != null &&
record.recipientLatitude != null &&
record.recipientLongitude != null) {
matched = true;
total += Geolocator.distanceBetween(
recipientLatitude,
recipientLongitude,
record.recipientLatitude!,
record.recipientLongitude!,
);
}
return matched ? total : double.infinity;
}
}

View File

@@ -1,72 +0,0 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../providers/connection_provider.dart';
/// Discovers available regions from repeater contacts via anonymous requests.
///
/// The firmware repeater responds to ANON_REQ_TYPE_REGIONS (0x01) with a
/// comma-separated list of region names that have flood allowed.
class RegionDiscoveryService {
static const int _anonReqTypeRegions = 0x01;
/// Discover regions from a single repeater.
///
/// Sends an anonymous request to the repeater and waits for the response.
/// Returns a list of region names (with `#` prefix).
/// Returns empty list on timeout or error.
static Future<List<String>> discoverFromRepeater({
required Uint8List repeaterPublicKey,
required ConnectionProvider connectionProvider,
Duration timeout = const Duration(seconds: 10),
}) async {
final result = await connectionProvider.sendAnonRequest(
contactPublicKey: repeaterPublicKey,
requestData: Uint8List.fromList([_anonReqTypeRegions]),
);
if (result == null) return [];
final tag = result.tag;
final completer = Completer<List<String>>();
void onResponse(Uint8List publicKeyPrefix, int responseTag, Uint8List data) {
if (responseTag != tag || completer.isCompleted) return;
completer.complete(_parseRegionResponse(data));
}
connectionProvider.onBinaryResponse = onResponse;
try {
return await completer.future.timeout(
timeout,
onTimeout: () => <String>[],
);
} catch (e) {
debugPrint('⚠️ [RegionDiscovery] Error discovering regions: $e');
return [];
} finally {
// Restore previous handler — callers should re-set if needed
if (connectionProvider.onBinaryResponse == onResponse) {
connectionProvider.onBinaryResponse = null;
}
}
}
/// Parse the region response payload.
///
/// Format: [4B sender_timestamp][4B repeater_clock][comma-separated names]
/// Names are returned without `#` prefix from firmware; we add it back.
static List<String> _parseRegionResponse(Uint8List data) {
if (data.length <= 8) return [];
final namesStr = utf8.decode(data.sublist(8), allowMalformed: true).trim();
if (namesStr.isEmpty || namesStr == '-none-') return [];
return namesStr
.split(',')
.map((name) => name.trim())
.where((name) => name.isNotEmpty && name != '*' && !name.startsWith('\$'))
.map((name) => name.startsWith('#') ? name : '#$name')
.toList();
}
}

View File

@@ -20,6 +20,30 @@ Future<void> _initializeConnectedWorkspace({
await appProvider.initialize();
}
String _normalizeConnectionError(Object error) {
var message = error.toString();
if (message.startsWith('Exception: ')) {
message = message.substring('Exception: '.length);
}
if (message.startsWith('Connection failed: Exception: ')) {
return message.substring('Connection failed: Exception: '.length);
}
if (message.startsWith('Connection failed: ')) {
return message.substring('Connection failed: '.length);
}
return message;
}
void _showConnectionErrorSnackBar(BuildContext context, Object error) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(_normalizeConnectionError(error)),
backgroundColor: Colors.red,
duration: const Duration(seconds: 5),
),
);
}
Future<bool> showConnectionDialogFlow(
BuildContext context, {
Color? backgroundColor,
@@ -36,6 +60,21 @@ Future<bool> showConnectionDialogFlow(
return result == _ConnectionDialogResult.connected;
}
try {
await _initializeConnectedWorkspace(
profileWorkspaceCoordinator: context.read<ProfileWorkspaceCoordinator>(),
appProvider: context.read<AppProvider>(),
);
} catch (error) {
if (context.mounted) {
_showConnectionErrorSnackBar(context, error);
}
}
if (!context.mounted) {
return true;
}
if (!offerPostConnectRepeaterDiscovery) {
return true;
}
@@ -182,43 +221,14 @@ class _ConnectionDialogState extends State<ConnectionDialog>
return Colors.red;
}
Future<void> _handleSuccessfulConnection() async {
final appProvider = context.read<AppProvider>();
final profileWorkspaceCoordinator = context
.read<ProfileWorkspaceCoordinator>();
await _initializeConnectedWorkspace(
profileWorkspaceCoordinator: profileWorkspaceCoordinator,
appProvider: appProvider,
);
void _closeOnSuccessfulConnection() {
if (!mounted) return;
Navigator.of(context).pop(_ConnectionDialogResult.connected);
}
String _normalizeConnectionError(Object error) {
var message = error.toString();
if (message.startsWith('Exception: ')) {
message = message.substring('Exception: '.length);
}
if (message.startsWith('Connection failed: Exception: ')) {
return message.substring('Connection failed: Exception: '.length);
}
if (message.startsWith('Connection failed: ')) {
return message.substring('Connection failed: '.length);
}
return message;
}
void _showConnectionError(Object error) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(_normalizeConnectionError(error)),
backgroundColor: Colors.red,
duration: const Duration(seconds: 5),
),
);
_showConnectionErrorSnackBar(context, error);
}
@override
@@ -554,7 +564,7 @@ class _ConnectionDialogState extends State<ConnectionDialog>
'Failed to connect to $name',
);
}
await _handleSuccessfulConnection();
_closeOnSuccessfulConnection();
} catch (error) {
_showConnectionError(error);
} finally {
@@ -676,7 +686,7 @@ class _ConnectionDialogState extends State<ConnectionDialog>
'Failed to connect to ${server.ipAddress}:${server.port}',
);
}
await _handleSuccessfulConnection();
_closeOnSuccessfulConnection();
} catch (e) {
if (!mounted) return;
setState(() {
@@ -883,11 +893,6 @@ class _SerialDeviceListState extends State<_SerialDeviceList> {
if (!mounted) return;
if (success) {
await _initializeConnectedWorkspace(
profileWorkspaceCoordinator: context
.read<ProfileWorkspaceCoordinator>(),
appProvider: context.read<AppProvider>(),
);
widget.onConnected(_ConnectionDialogResult.connected);
} else {
await connection.disconnect();

View File

@@ -157,6 +157,7 @@ class ContactTile extends StatelessWidget {
icon: Icons.folder_copy_outlined,
label: label,
),
..._buildSignalPills(context),
],
),
if (location != null) ...[
@@ -324,6 +325,34 @@ class ContactTile extends StatelessWidget {
);
}
List<Widget> _buildSignalPills(BuildContext context) {
if (!contact.isRepeater && !contact.isSensor) return [];
final contactsProvider = context.read<ContactsProvider>();
final advert = contactsProvider.pendingAdvertByKey(contact.publicKey);
if (advert == null) return [];
final pills = <Widget>[];
if (advert.rxRssiDbm != null) {
pills.add(
_buildMetaPill(
context,
icon: Icons.arrow_downward_rounded,
label: '${advert.rxRssiDbm} dBm',
),
);
}
if (advert.repeaterLastRssi != null) {
pills.add(
_buildMetaPill(
context,
icon: Icons.arrow_upward_rounded,
label: '${advert.repeaterLastRssi} dBm',
),
);
}
return pills;
}
Widget _buildCompactSubtitle(BuildContext context, String? distanceText) {
final location = contact.displayLocation;
final compactPills = <Widget>[
@@ -338,6 +367,7 @@ class ContactTile extends StatelessWidget {
icon: Icons.location_disabled_outlined,
label: AppLocalizations.of(context)!.noGpsData,
),
..._buildSignalPills(context),
];
return Padding(

View File

@@ -12,6 +12,7 @@ import '../../models/sar_template.dart';
import '../../models/map_drawing.dart';
import '../../models/map_coordinate_space.dart';
import '../../providers/messages_provider.dart';
import '../../providers/channels_provider.dart';
import '../../providers/contacts_provider.dart';
import '../../providers/connection_provider.dart';
import '../../providers/drawing_provider.dart';
@@ -1955,10 +1956,12 @@ class _MessageBubbleState extends State<MessageBubble> {
final isSarMarker = message.isSarMarker;
final isDarkMode = Theme.of(context).brightness == Brightness.dark;
final messageFontScale = context.watch<AppProvider>().messageFontScale;
final l10n = AppLocalizations.of(context)!;
// Determine if this is own message
final connectionProvider = context.read<ConnectionProvider>();
final messagesProvider = context.read<MessagesProvider>();
final channelsProvider = context.watch<ChannelsProvider>();
final selfPublicKey = connectionProvider.deviceInfo.publicKey;
final isOwnMessage =
message.isSentMessage || message.isFromSelf(selfPublicKey);
@@ -2004,7 +2007,7 @@ class _MessageBubbleState extends State<MessageBubble> {
// Get rich display name (with emoji if available)
final displayName = isOwnMessage
? AppLocalizations.of(context)!.you
? l10n.you
: message.getRichDisplayName(senderContact);
// Look up destination/source display labels for direct/channel messages
@@ -2039,15 +2042,30 @@ class _MessageBubbleState extends State<MessageBubble> {
}
}
} else if (message.isChannelMessage) {
if (message.channelIdx == 0) {
channelDisplayName = AppLocalizations.of(context)!.publicChannel;
final channelIdx = message.channelIdx ?? 0;
if (channelIdx == 0) {
channelDisplayName = l10n.publicChannel;
} else {
final channelContact = contactsProvider.channels.where((c) {
return c.publicKey.length > 1 && c.publicKey[1] == message.channelIdx;
return c.publicKey.length > 1 && c.publicKey[1] == channelIdx;
}).firstOrNull;
final syncedChannel = channelsProvider.getChannel(channelIdx);
final syncedChannelDisplayName =
syncedChannel != null && syncedChannel.hasCustomName
? syncedChannel.displayName
: null;
final contactChannelDisplayName = channelContact
?.getLocalizedDisplayName(context)
.trim();
channelDisplayName =
channelContact?.getLocalizedDisplayName(context) ??
'${AppLocalizations.of(context)!.channel} ${message.channelIdx}';
syncedChannelDisplayName ??
(contactChannelDisplayName != null &&
contactChannelDisplayName.isNotEmpty
? contactChannelDisplayName
: null) ??
syncedChannel?.displayName ??
'${l10n.channel} $channelIdx';
}
if (isOwnMessage) {
@@ -2057,14 +2075,14 @@ class _MessageBubbleState extends State<MessageBubble> {
final recipientSubtitle =
isOwnMessage && message.isChannelMessage && recipientDisplayName != null
? '${AppLocalizations.of(context)!.channel}: $recipientDisplayName'
? '${l10n.channel}: $recipientDisplayName'
: recipientDisplayName;
final directCounterpartLabel = !message.isChannelMessage
? (isOwnMessage ? recipientSubtitle : AppLocalizations.of(context)!.you)
? (isOwnMessage ? recipientSubtitle : l10n.you)
: null;
final receivedChannelSubtitle =
!isOwnMessage && message.isChannelMessage && channelDisplayName != null
? '${AppLocalizations.of(context)!.channel}: $channelDisplayName'
? '${l10n.channel}: $channelDisplayName'
: null;
final shouldFloatBubble = widget.isCompact;

View File

@@ -1,7 +1,10 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../l10n/app_localizations.dart';
import '../../models/contact.dart';
import '../../providers/messages_provider.dart';
import '../../utils/avatar_label_helper.dart';
import '../common/contact_avatar.dart';
enum _RecipientSortMode { activity, favorites, alphabetical }
@@ -17,6 +20,7 @@ class RecipientSelectorSheet extends StatefulWidget {
final String? currentRecipientPublicKey;
final bool showAllOption;
final Function(String type, Contact? recipient) onSelect;
final MessagesProvider? messagesProvider;
/// Region scope names per channel index (e.g. {0: "#auckland"}).
final Map<int, String> channelRegionScopes;
@@ -32,6 +36,7 @@ class RecipientSelectorSheet extends StatefulWidget {
this.currentRecipientPublicKey,
this.showAllOption = true,
required this.onSelect,
this.messagesProvider,
this.channelRegionScopes = const {},
});
@@ -167,20 +172,162 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
}
}
String _channelSubtitle(BuildContext context, Contact channel) {
final l10n = AppLocalizations.of(context)!;
final channelIdx = channel.publicKey.length > 1 ? channel.publicKey[1] : 0;
final scopeName = widget.channelRegionScopes[channelIdx];
if (channel.isPublicChannel) {
return scopeName != null
? '${l10n.broadcastToAllNearby}$scopeName'
: l10n.broadcastToAllNearby;
MessagesProvider? _resolveMessagesProvider(BuildContext context) {
if (widget.messagesProvider != null) {
return widget.messagesProvider;
}
final shortKey = channel.publicKeyShort.toUpperCase();
final base = '${l10n.channel} $channelIdx$shortKey';
return scopeName != null ? '$base$scopeName' : base;
try {
return Provider.of<MessagesProvider>(context);
} on ProviderNotFoundException {
return null;
}
}
String _formatRelativeTime(BuildContext context, DateTime when) {
final l10n = AppLocalizations.of(context)!;
final diff = DateTime.now().difference(when);
if (diff.inMinutes < 1) return l10n.justNow;
if (diff.inMinutes < 60) return l10n.minutesAgo(diff.inMinutes);
if (diff.inHours < 24) return l10n.hoursAgo(diff.inHours);
return l10n.daysAgo(diff.inDays);
}
_ChannelPreviewData _channelPreviewData(
BuildContext context,
Contact channel,
MessagesProvider? messagesProvider,
) {
if (messagesProvider == null) {
return const _ChannelPreviewData();
}
final lastActivityAt = messagesProvider.getLastActivityForDestination(
channel,
);
final channelIdx = channel.publicKey.length > 1 ? channel.publicKey[1] : 0;
final channelMessages = messagesProvider.getMessagesForChannel(channelIdx)
..sort((a, b) => b.sentAt.compareTo(a.sentAt));
final participantNames = <String>[];
for (final message in channelMessages) {
final senderName = message.senderName?.trim();
if (senderName == null || senderName.isEmpty) {
continue;
}
if (!participantNames.contains(senderName)) {
participantNames.add(senderName);
}
}
return _ChannelPreviewData(
activityLabel: lastActivityAt == null
? null
: _formatRelativeTime(context, lastActivityAt),
participantNames: participantNames,
);
}
Contact? _findParticipantContact(String name) {
final normalizedName = name.trim();
for (final contact in widget.contacts) {
if (!contact.isChannel && contact.advName.trim() == normalizedName) {
return contact;
}
}
for (final contact in widget.contacts) {
if (!contact.isChannel && contact.displayName.trim() == normalizedName) {
return contact;
}
}
return null;
}
String _contactActivityLabel(
BuildContext context,
Contact contact,
MessagesProvider? messagesProvider,
) {
final lastActivityAt =
messagesProvider?.getLastActivityForDestination(contact) ??
contact.lastSeenTime;
return _formatRelativeTime(context, lastActivityAt);
}
Widget _buildTextSubtitle(
BuildContext context,
Contact contact,
String subtitle,
) {
final colorScheme = Theme.of(context).colorScheme;
return Text(
subtitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontFamily: contact.isChannel ? null : 'monospace',
),
);
}
Widget _buildChannelSubtitle(
BuildContext context,
Contact channel,
_ChannelPreviewData previewData,
) {
final colorScheme = Theme.of(context).colorScheme;
if (previewData.participantNames.isEmpty) {
return Text(
'No recent chatters',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(
context,
).textTheme.bodySmall?.copyWith(color: colorScheme.onSurfaceVariant),
);
}
return Row(
children: [
_ParticipantAvatarStack(
key: Key('channel-participants-${channel.publicKeyHex}'),
names: previewData.participantNames,
contactForName: _findParticipantContact,
),
],
);
}
Widget _buildChannelRecipientCard(
BuildContext context,
Contact channel,
MessagesProvider? messagesProvider,
) {
final previewData = _channelPreviewData(context, channel, messagesProvider);
return _buildRecipientCard(
context: context,
type: 'channel',
contact: channel,
title: channel.getLocalizedDisplayName(context),
subtitle: _buildChannelSubtitle(context, channel, previewData),
unreadCount: _unreadFor(channel),
isSelected: _isSelected('channel', channel),
compact: true,
activityLabel: previewData.activityLabel,
onTap: () {
widget.onSelect('channel', channel);
Navigator.pop(context);
},
);
}
bool _isDenseSection(String type) => type == 'channel' || type == 'contact';
@@ -189,6 +336,7 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final colorScheme = Theme.of(context).colorScheme;
final messagesProvider = _resolveMessagesProvider(context);
final filteredContacts = _filterAndSortContacts(widget.contacts);
final filteredRooms = _filterAndSortContacts(widget.rooms);
final filteredChannels = _filterAndSortContacts(
@@ -335,19 +483,10 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
emptyLabel: l10n.noChannelsFound,
children: [
for (final channel in filteredChannels)
_buildRecipientCard(
context: context,
type: 'channel',
contact: channel,
title: channel.getLocalizedDisplayName(context),
subtitle: _channelSubtitle(context, channel),
unreadCount: _unreadFor(channel),
isSelected: _isSelected('channel', channel),
compact: true,
onTap: () {
widget.onSelect('channel', channel);
Navigator.pop(context);
},
_buildChannelRecipientCard(
context,
channel,
messagesProvider,
),
],
),
@@ -366,7 +505,11 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
type: 'contact',
contact: contact,
title: contact.displayName,
subtitle: contact.publicKeyShort,
activityLabel: _contactActivityLabel(
context,
contact,
messagesProvider,
),
unreadCount: _unreadFor(contact),
isSelected: _isSelected('contact', contact),
compact: true,
@@ -392,7 +535,11 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
type: 'room',
contact: room,
title: room.displayName,
subtitle: room.publicKeyShort,
subtitle: _buildTextSubtitle(
context,
room,
room.publicKeyShort,
),
unreadCount: _unreadFor(room),
isSelected: _isSelected('room', room),
onTap: () {
@@ -690,10 +837,11 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
required String type,
required Contact contact,
required String title,
required String subtitle,
Widget? subtitle,
required int unreadCount,
required bool isSelected,
bool compact = false,
String? activityLabel,
required VoidCallback onTap,
}) {
final colorScheme = Theme.of(context).colorScheme;
@@ -757,52 +905,70 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
child: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall
?.copyWith(
fontWeight: FontWeight.w800,
letterSpacing: -0.2,
Expanded(
child: Row(
children: [
Flexible(
child: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context)
.textTheme
.titleSmall
?.copyWith(
fontWeight: FontWeight.w800,
letterSpacing: -0.2,
),
),
),
if (contact.isPublicChannel) ...[
SizedBox(width: compact ? 6 : 8),
Container(
padding: EdgeInsets.symmetric(
horizontal: compact ? 7 : 8,
vertical: compact ? 2 : 3,
),
decoration: BoxDecoration(
color: accentColor.withValues(
alpha: 0.10,
),
borderRadius: BorderRadius.circular(999),
),
child: Text(
'Public',
style: Theme.of(context)
.textTheme
.labelSmall
?.copyWith(
color: accentColor,
fontWeight: FontWeight.w800,
),
),
),
],
],
),
),
if (contact.isPublicChannel) ...[
SizedBox(width: compact ? 6 : 8),
Container(
padding: EdgeInsets.symmetric(
horizontal: compact ? 7 : 8,
vertical: compact ? 2 : 3,
),
decoration: BoxDecoration(
color: accentColor.withValues(alpha: 0.10),
borderRadius: BorderRadius.circular(999),
),
child: Text(
'Public',
style: Theme.of(context).textTheme.labelSmall
?.copyWith(
color: accentColor,
fontWeight: FontWeight.w800,
),
),
if (activityLabel != null) ...[
SizedBox(width: compact ? 8 : 10),
Text(
activityLabel,
style: Theme.of(context).textTheme.labelSmall
?.copyWith(
color: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w700,
),
),
],
],
),
SizedBox(height: compact ? 2 : 4),
Text(
if (subtitle != null) ...[
SizedBox(height: compact ? 2 : 4),
subtitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontFamily: contact.isChannel ? null : 'monospace',
),
),
],
],
),
),
@@ -858,3 +1024,140 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
);
}
}
class _ChannelPreviewData {
final String? activityLabel;
final List<String> participantNames;
const _ChannelPreviewData({
this.activityLabel,
this.participantNames = const <String>[],
});
}
class _ParticipantAvatarStack extends StatelessWidget {
final List<String> names;
final Contact? Function(String name) contactForName;
static const int _visibleCount = 4;
const _ParticipantAvatarStack({
super.key,
required this.names,
required this.contactForName,
});
@override
Widget build(BuildContext context) {
final visibleNames = names.take(_visibleCount).toList();
final overflowCount = names.length - visibleNames.length;
const avatarSize = 20.0;
const spacing = 14.0;
final itemCount = visibleNames.length + (overflowCount > 0 ? 1 : 0);
final width = itemCount == 0 ? 0.0 : avatarSize + (itemCount - 1) * spacing;
return SizedBox(
width: width,
height: avatarSize,
child: Stack(
clipBehavior: Clip.none,
children: [
for (var i = 0; i < visibleNames.length; i++)
Positioned(
left: i * spacing,
top: 0,
child: _ParticipantAvatar(
name: visibleNames[i],
contact: contactForName(visibleNames[i]),
),
),
if (overflowCount > 0)
Positioned(
left: visibleNames.length * spacing,
top: 0,
child: _ParticipantOverflowAvatar(count: overflowCount),
),
],
),
);
}
}
class _ParticipantOverflowAvatar extends StatelessWidget {
final int count;
const _ParticipantOverflowAvatar({required this.count});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Container(
width: 20,
height: 20,
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest,
shape: BoxShape.circle,
border: Border.all(color: colorScheme.surface, width: 2),
),
alignment: Alignment.center,
child: Text(
'+$count',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
fontWeight: FontWeight.w700,
color: colorScheme.onSurface,
fontSize: 8,
),
),
);
}
}
class _ParticipantAvatar extends StatelessWidget {
final String name;
final Contact? contact;
const _ParticipantAvatar({required this.name, required this.contact});
@override
Widget build(BuildContext context) {
if (contact != null) {
final surfaceColor = Theme.of(context).colorScheme.surface;
return SizedBox(
width: 20,
height: 20,
child: DecoratedBox(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: surfaceColor, width: 2),
),
child: Padding(
padding: const EdgeInsets.all(2),
child: ClipOval(child: ContactAvatar(contact: contact!, radius: 6)),
),
),
);
}
final colorScheme = Theme.of(context).colorScheme;
return Container(
width: 20,
height: 20,
decoration: BoxDecoration(
color: colorScheme.tertiaryContainer,
shape: BoxShape.circle,
border: Border.all(color: colorScheme.surface, width: 2),
),
alignment: Alignment.center,
child: Text(
AvatarLabelHelper.buildLabel(name),
style: Theme.of(context).textTheme.labelSmall?.copyWith(
fontWeight: FontWeight.w700,
color: colorScheme.onTertiaryContainer,
fontSize: 8,
),
),
);
}
}

View File

@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 2026.0322.1+38
version: 2026.0322.2+39
environment:
sdk: ^3.9.2

View File

@@ -206,4 +206,59 @@ void main() {
expect(history.directPaths.single.source, PathRecordSource.observed);
},
);
test('last successful direct path is chosen by location fit', () async {
final service = PathHistoryService();
final contact = _buildContact(
seed: 7,
pathBytes: [0xAA],
hopCount: 1,
hashSize: 1,
);
await service.initialize();
await service.recordPathResult(
contact.publicKeyHex,
PathSelection(
mode: PathSelectionMode.directHistorical,
pathBytes: Uint8List.fromList([0x11]),
hopCount: 1,
hashSize: 1,
),
success: true,
roundTripTimeMs: 120,
senderLatitude: 46.0,
senderLongitude: 14.0,
recipientLatitude: 46.1,
recipientLongitude: 14.1,
);
await service.recordPathResult(
contact.publicKeyHex,
PathSelection(
mode: PathSelectionMode.directHistorical,
pathBytes: Uint8List.fromList([0x22]),
hopCount: 1,
hashSize: 1,
),
success: true,
roundTripTimeMs: 90,
senderLatitude: 46.0001,
senderLongitude: 14.0001,
recipientLatitude: 46.1001,
recipientLongitude: 14.1001,
);
final selection = await service.getLastSuccessfulDirectSelection(
contact,
excludeSignature: 'aa',
senderLatitude: 46.0002,
senderLongitude: 14.0002,
recipientLatitude: 46.1002,
recipientLongitude: 14.1002,
);
expect(selection, isNotNull);
expect(selection!.mode, PathSelectionMode.directHistorical);
expect(selection.canonicalPath, '22');
});
}

View File

@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/l10n/app_localizations.dart';
import 'package:meshcore_sar_app/providers/connection_provider.dart';
@@ -34,6 +35,24 @@ class _FakeConnectionProvider extends ConnectionProvider {
}
}
class _ConnectableFakeConnectionProvider extends ConnectionProvider {
int connectCalls = 0;
@override
List<ScannedDevice> get scannedDevices => [
ScannedDevice(device: BluetoothDevice.fromId('test-device'), rssi: -55),
];
@override
String? get error => null;
@override
Future<bool> connect(BluetoothDevice device) async {
connectCalls += 1;
return true;
}
}
void main() {
testWidgets('BLE scan waits for explicit user action', (tester) async {
final connectionProvider = _FakeConnectionProvider();
@@ -64,4 +83,47 @@ void main() {
expect(connectionProvider.stopScanCalls, 1);
expect(connectionProvider.startScanCalls, 1);
});
testWidgets('successful BLE connect closes the dialog immediately', (
tester,
) async {
final connectionProvider = _ConnectableFakeConnectionProvider();
await tester.pumpWidget(
ChangeNotifierProvider<ConnectionProvider>.value(
value: connectionProvider,
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Builder(
builder: (context) => Scaffold(
body: Center(
child: FilledButton(
onPressed: () {
showModalBottomSheet<Object?>(
context: context,
isScrollControlled: true,
builder: (_) => const ConnectionDialog(),
);
},
child: const Text('Open'),
),
),
),
),
),
),
);
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
expect(find.byType(ConnectionDialog), findsOneWidget);
await tester.tap(find.widgetWithText(FilledButton, 'Connect'));
await tester.pumpAndSettle();
expect(connectionProvider.connectCalls, 1);
expect(find.byType(ConnectionDialog), findsNothing);
});
}

View File

@@ -181,6 +181,44 @@ void main() {
}
});
testWidgets('channel bubbles refresh to synced channel names', (
tester,
) async {
final harness = await _TestHarness.create();
try {
final message = Message(
id: 'channel-name-refresh',
messageType: MessageType.channel,
senderPublicKeyPrefix: _prefix(61),
channelIdx: 3,
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: 1700000000,
text: 'Team update',
receivedAt: DateTime.fromMillisecondsSinceEpoch(1700000000500),
deliveryStatus: MessageDeliveryStatus.sent,
);
await tester.pumpWidget(_buildApp(harness, message));
await tester.pumpAndSettle();
expect(find.text('Channel 3'), findsOneWidget);
expect(find.text('#slovenija'), findsNothing);
harness.channelsProvider.addOrUpdateChannel(
index: 3,
name: '#slovenija',
secret: Uint8List(16),
);
await tester.pumpAndSettle();
expect(find.text('#slovenija'), findsOneWidget);
expect(find.text('Channel 3'), findsNothing);
} finally {
await _disposeHarness(tester, harness);
}
});
testWidgets('message bubble detects and opens links', (tester) async {
final harness = await _TestHarness.create();
try {

View File

@@ -4,6 +4,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/l10n/app_localizations.dart';
import 'package:meshcore_sar_app/models/contact.dart';
import 'package:meshcore_sar_app/models/message.dart';
import 'package:meshcore_sar_app/providers/messages_provider.dart';
import 'package:meshcore_sar_app/widgets/messages/recipient_selector_sheet.dart';
void main() {
@@ -31,13 +33,18 @@ void main() {
);
}
Future<void> pumpSheet(WidgetTester tester) async {
final channel = buildContact(
name: 'Ops',
type: ContactType.channel,
secondByte: 3,
);
final contact = buildContact(name: 'John Smith', type: ContactType.chat);
Future<void> pumpSheet(
WidgetTester tester, {
List<Contact>? contacts,
List<Contact>? channels,
MessagesProvider? messagesProvider,
bool showAllOption = true,
}) async {
final resolvedChannels =
channels ??
[buildContact(name: 'Ops', type: ContactType.channel, secondByte: 3)];
final resolvedContacts =
contacts ?? [buildContact(name: 'John Smith', type: ContactType.chat)];
await tester.pumpWidget(
MaterialApp(
@@ -45,15 +52,17 @@ void main() {
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: RecipientSelectorSheet(
contacts: [contact],
contacts: resolvedContacts,
rooms: const [],
channels: [channel],
channels: resolvedChannels,
unreadCount: 11,
unreadCountsByPublicKey: {
channel.publicKeyHex: 7,
contact.publicKeyHex: 3,
for (final channel in resolvedChannels) channel.publicKeyHex: 7,
for (final contact in resolvedContacts) contact.publicKeyHex: 3,
},
currentDestinationType: 'all',
showAllOption: showAllOption,
messagesProvider: messagesProvider,
onSelect: (selectedContact, destinationType) {},
),
),
@@ -150,4 +159,88 @@ void main() {
expect(charlieY, lessThan(bravoY));
expect(bravoY, lessThan(alphaY));
});
testWidgets('shows channel activity and participants instead of raw ids', (
tester,
) async {
final channel = buildContact(
name: 'Ops',
type: ContactType.channel,
secondByte: 3,
);
final messagesProvider = MessagesProvider()
..addMessage(
Message(
id: 'channel-activity',
messageType: MessageType.channel,
senderName: 'Radio Alpha',
channelIdx: 3,
pathLen: 1,
textType: MessageTextType.plain,
senderTimestamp:
DateTime.now()
.subtract(const Duration(minutes: 5))
.millisecondsSinceEpoch ~/
1000,
text: 'status update',
receivedAt: DateTime.now().subtract(const Duration(minutes: 5)),
),
);
await pumpSheet(
tester,
contacts: const [],
channels: [channel],
messagesProvider: messagesProvider,
showAllOption: false,
);
expect(
find.byKey(Key('channel-participants-${channel.publicKeyHex}')),
findsOneWidget,
);
expect(find.text('Radio Alpha'), findsNothing);
expect(find.text('5m ago'), findsOneWidget);
expect(find.textContaining('Channel 3'), findsNothing);
expect(find.text(channel.publicKeyShort.toUpperCase()), findsNothing);
});
testWidgets('shows contact activity instead of the public key', (
tester,
) async {
final contact = buildContact(
name: 'John Smith',
type: ContactType.chat,
secondByte: 4,
);
final messagesProvider = MessagesProvider()
..addMessage(
Message(
id: 'contact-activity',
messageType: MessageType.contact,
recipientPublicKey: contact.publicKey,
pathLen: 1,
textType: MessageTextType.plain,
senderTimestamp:
DateTime.now()
.subtract(const Duration(hours: 2))
.millisecondsSinceEpoch ~/
1000,
text: 'check-in',
receivedAt: DateTime.now().subtract(const Duration(hours: 2)),
),
);
await pumpSheet(
tester,
contacts: [contact],
channels: const [],
messagesProvider: messagesProvider,
showAllOption: false,
);
expect(find.text('John Smith'), findsOneWidget);
expect(find.text('2h ago'), findsOneWidget);
expect(find.text(contact.publicKeyShort), findsNothing);
});
}