Fix list ordering and long-list scrolling

- Sort channels by latest message and contacts by recent message using local
  arrival time instead of the sender's clock.
- Contacts added from a card sort by when they were added until the radio
  hears an advert (app-side only; lastAdvert stays 0).
- Stop entrance animations on rows scrolled into view and reuse unchanged
  contact rows across connector updates.
This commit is contained in:
zjs81 committed 2026-11-20 16:37:47 -07:00
1 parent 34ea0cb7ca
commit 316088dfd6
35 files changed
+1357 -43

No files matched your search

+152
View File
@@ -0,0 +1,152 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/storage/contact_added_at_store.dart';
import 'package:meshcore_open/storage/last_radio_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/utils/contact_qr.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<void> _waitFor(bool Function() condition, {int seconds = 8}) async {
final end = DateTime.now().add(Duration(seconds: seconds));
while (!condition()) {
if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition');
await Future<void>.delayed(const Duration(milliseconds: 25));
}
}
class _RecordingReviewRadio extends ReviewRadio {
final List<Uint8List> sent = [];
_RecordingReviewRadio()
: super(scheduledMessageInterval: const Duration(hours: 1));
@override
void handle(Uint8List frame) {
sent.add(frame);
super.handle(frame);
}
}
// [cmd][pub_key x32][type][flags][path_len][path x64][name x32][last_advert x4]
const _lastAdvertOffset = 1 + 32 + 1 + 1 + 1 + 64 + 32;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
test(
'a card add records a local added time once, never on the radio',
() async {
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
final retryService = MessageRetryService();
addTearDown(retryService.dispose);
connector.initialize(
retryService: retryService,
pathHistoryService: PathHistoryService(StorageService()),
);
final radio = _RecordingReviewRadio();
connector.reviewRadioFactoryForTest = () => radio;
await connector.connectReview();
await _waitFor(() => connector.hasLoadedContacts);
final key = Uint8List.fromList(List.generate(32, (i) => 0xA0 + (i % 16)));
final keyHex = pubKeyToHex(key);
final card = ScannedContact(publicKey: key, name: 'Card', type: 1);
final before = DateTime.now();
await connector.addContactFromCard(card);
final addedAt = connector.contactAddedAt(keyHex);
expect(addedAt, isNotNull);
expect(addedAt!.isBefore(before), isFalse);
// The radio still gets advert time 0 (its replay guard).
final addFrame = radio.sent.lastWhere(
(f) => f.first == cmdAddUpdateContact,
);
expect(
ByteData.sublistView(
addFrame,
).getUint32(_lastAdvertOffset, Endian.little),
0,
);
// Re-adding keeps the first time.
await Future<void>.delayed(const Duration(milliseconds: 5));
await connector.addContactFromCard(card);
expect(connector.contactAddedAt(keyHex), addedAt);
// Persisted per radio.
final store = ContactAddedAtStore()
..setPublicKeyHex = connector.selfPublicKeyHex;
expect(
store.load()[keyHex]?.millisecondsSinceEpoch,
addedAt.millisecondsSinceEpoch,
);
final otherRadio = ContactAddedAtStore()
..setPublicKeyHex = 'ffffffffff00';
expect(otherRadio.load(), isEmpty);
// Removing the contact forgets it, so a later add starts fresh.
await connector.removeContact(
Contact(
publicKey: key,
name: 'Card',
type: 1,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
),
);
expect(connector.contactAddedAt(keyHex), isNull);
// So does the firmware deleting it to make room.
await connector.addContactFromCard(card);
expect(connector.contactAddedAt(keyHex), isNotNull);
connector.handleFrameForTest([pushCodeContactDeleted, ...key]);
expect(connector.contactAddedAt(keyHex), isNull);
await Future<void>.delayed(Duration.zero);
expect(store.load(), isNot(contains(keyHex)));
await connector.disconnect(manual: true);
},
);
test('a saved radio restores its added times after a restart', () async {
const radioHex =
'a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf';
final contactHex = 'c1' * 32;
final addedAt = DateTime.fromMillisecondsSinceEpoch(1790000000000);
await (ContactAddedAtStore()..setPublicKeyHex = radioHex).save({
contactHex: addedAt,
});
await LastRadioStore().save(
LastRadio(
publicKeyHex: radioHex,
name: 'Base',
transport: LastRadio.transportBle,
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
savedAt: addedAt,
),
);
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
await connector.restoreLastRadio();
expect(connector.contactAddedAt(contactHex), addedAt);
});
}
+356
View File
@@ -0,0 +1,356 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/screens/channels_screen.dart';
import 'package:meshcore_open/screens/contacts_screen.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/mesh_ui.dart';
/// Repeatable stand-in for profiling rapid scrolling on a phone: builds the
/// contacts list with 500 contacts and the channels list with 40 channels,
/// flings each list, and counts widget builds and rows that are not fully
/// drawn while scrolling. Run with `flutter test
/// test/screens/list_scroll_perf_test.dart` and read the printed lines.
/// See documentation/performance-profiling.md for the on-device check.
const _contactCount = 500;
const _channelCount = 40;
class _Connector extends MeshCoreConnector {
List<Contact> nodes = [];
List<Channel> slots = [];
final Map<String, int> unread = {};
final Map<int, ChannelMessage> latest = {};
@override
List<Contact> get contacts => List.unmodifiable(nodes);
@override
List<Channel> get channels => List.unmodifiable(slots);
@override
int getUnreadCountForContact(Contact contact) =>
unread[contact.publicKeyHex] ?? 0;
@override
int getUnreadCountForChannel(Channel channel) => channel.unreadCount;
@override
ChannelMessage? latestVisibleChannelMessage(Channel channel) =>
latest[channel.index];
@override
Future<void> getChannels({int? maxChannels, bool force = false}) async {}
}
Contact _contact(int i, DateTime now) {
final key = Uint8List(32)
..[0] = i >> 8
..[1] = i & 0xff
..[2] = 0x5a;
final type = i % 10 == 0
? advTypeRepeater
: i % 25 == 0
? advTypeRoom
: advTypeChat;
return Contact(
publicKey: key,
name: 'Node ${i.toString().padLeft(3, '0')}',
type: type,
pathLength: i % 4,
path: Uint8List.fromList(List.filled(i % 4, i & 0xff)),
latitude: i.isEven ? 35.0 : null,
longitude: i.isEven ? -112.0 : null,
lastSeen: now.subtract(Duration(minutes: i * 7)),
);
}
/// Counts element builds per widget type, via the framework's debug hook.
class _BuildCounter {
final Map<String, int> counts = {};
void start() {
counts.clear();
debugOnRebuildDirtyWidget = (element, _) {
final name = element.widget.runtimeType.toString();
counts[name] = (counts[name] ?? 0) + 1;
};
}
void stop() => debugOnRebuildDirtyWidget = null;
int operator [](String type) => counts[type] ?? 0;
int get total => counts.values.fold(0, (a, b) => a + b);
}
/// Rows inside the visible list area whose entrance fade has not finished:
/// they are blank or partly transparent while the user scrolls.
int _rowsNotFullyDrawn(WidgetTester tester, Rect viewport) {
final fades = find.descendant(
of: find.byType(ListEntrance),
matching: find.byType(FadeTransition),
);
var count = 0;
for (final element in fades.evaluate()) {
final fade = element.widget as FadeTransition;
final box = element.renderObject as RenderBox?;
if (box == null || !box.attached || !box.hasSize) continue;
final rect = box.localToGlobal(Offset.zero) & box.size;
if (!rect.overlaps(viewport)) continue;
if (fade.opacity.value < 1) count++;
}
return count;
}
class _ScrollResult {
int frames = 0;
int notFullyDrawnRowFrames = 0;
int maxNotFullyDrawn = 0;
int notFullyDrawnAfterStop = 0;
}
/// Flings [list] like a rapid swipe and pumps 60 Hz frames until the list
/// stops, firing a connector notify partway through.
Future<_ScrollResult> _fling(
WidgetTester tester,
Finder list,
_Connector connector, {
required Offset offset,
}) async {
final viewport = tester.getRect(list);
final position = tester.state<ScrollableState>(
find.descendant(of: list, matching: find.byType(Scrollable)).first,
);
final result = _ScrollResult();
await tester.fling(list, offset, 6000);
for (var i = 0; i < 400; i++) {
if (i == 10) connector.notifyListeners();
await tester.pump(const Duration(milliseconds: 16));
result.frames++;
final hidden = _rowsNotFullyDrawn(tester, viewport);
result.notFullyDrawnRowFrames += hidden;
if (hidden > result.maxNotFullyDrawn) result.maxNotFullyDrawn = hidden;
if (i > 12 && !position.position.isScrollingNotifier.value) break;
}
result.notFullyDrawnAfterStop = _rowsNotFullyDrawn(tester, viewport);
return result;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late _Connector connector;
late AppSettingsService settings;
late UiViewStateService viewState;
final counter = _BuildCounter();
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
connector = _Connector();
settings = AppSettingsService();
viewState = UiViewStateService();
});
tearDown(() {
counter.stop();
connector.dispose();
settings.dispose();
viewState.dispose();
});
/// Opens [home] and returns how many rows played the entrance animation.
Future<int> open(WidgetTester tester, Widget home) async {
tester.view.physicalSize = const Size(1080, 2340);
tester.view.devicePixelRatio = 3;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider<MeshCoreConnector>.value(value: connector),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: viewState),
],
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: home,
),
),
);
await tester.pump();
final animatedRows = find
.descendant(
of: find.byType(ListEntrance),
matching: find.byType(FadeTransition),
)
.evaluate()
.length;
// Let the first screen's entrance animations finish.
for (var i = 0; i < 40; i++) {
await tester.pump(const Duration(milliseconds: 16));
}
return animatedRows;
}
Future<void> notifyAndSettle(WidgetTester tester) async {
connector.notifyListeners();
await tester.pump(const Duration(milliseconds: 60));
await tester.pump();
}
Future<void> close(WidgetTester tester) async {
counter.stop();
await tester.pumpWidget(const SizedBox.shrink());
// Drain entrance-delay timers.
await tester.pump(const Duration(seconds: 1));
}
testWidgets('contacts list: rapid fling with 500 contacts', (tester) async {
final now = DateTime.now();
connector.nodes = [
for (var i = 0; i < _contactCount; i++) _contact(i, now),
];
for (var i = 1; i < _contactCount; i += 9) {
connector.unread[connector.nodes[i].publicKeyHex] = i % 5 + 1;
}
final animatedRows = await open(tester, const ContactsScreen());
final list = find.byType(ListView);
expect(list, findsOneWidget);
counter.start();
final down = await _fling(
tester,
list,
connector,
offset: const Offset(0, -2500),
);
final flingBuilds = Map.of(counter.counts);
final flingTotal = counter.total;
counter.start();
await notifyAndSettle(tester);
final notifyTiles = counter['_ContactTile'];
final notifyTotal = counter.total;
// A live change still reaches the visible tile.
final visible = tester
.widgetList(
find.byWidgetPredicate(
(w) => w.runtimeType.toString() == '_ContactTile',
),
)
.map((w) => (w as dynamic).contact as Contact)
.toList();
final target = visible[visible.length ~/ 2];
connector.unread[target.publicKeyHex] = 42;
counter.start();
await notifyAndSettle(tester);
final changeTiles = counter['_ContactTile'];
expect(find.text('42'), findsOneWidget);
// So does a replaced contact.
final renamedAt = connector.nodes.indexOf(visible.first);
connector.nodes = List.of(connector.nodes)
..[renamedAt] = visible.first.copyWith(name: 'Renamed node');
await notifyAndSettle(tester);
expect(find.text('Renamed node'), findsOneWidget);
// ignore: avoid_print
print(
'[list-perf] contacts fling: frames=${down.frames} '
'itemBuilds=${flingBuilds['_ContactTileEntrance'] ?? 0} '
'tileBuilds=${flingBuilds['_ContactTile'] ?? 0} '
'entranceBuilds=${flingBuilds['ListEntrance'] ?? 0} '
'allBuilds=$flingTotal '
'rowFramesNotFullyDrawn=${down.notFullyDrawnRowFrames} '
'maxRowsNotFullyDrawn=${down.maxNotFullyDrawn} '
'rowsNotFullyDrawnAtStop=${down.notFullyDrawnAfterStop}\n'
'[list-perf] contacts notify (no change): tileBuilds=$notifyTiles '
'allBuilds=$notifyTotal; one unread change: tileBuilds=$changeTiles',
);
// The first screen still animates in; rows a fling brings in do not.
expect(animatedRows, greaterThan(0));
expect(down.notFullyDrawnRowFrames, 0);
// A notify that changes nothing rebuilds no rows; a change rebuilds one.
expect(notifyTiles, 0);
expect(changeTiles, 1);
await close(tester);
});
testWidgets('channels list: rapid fling with 40 channels', (tester) async {
final now = DateTime.now();
connector.slots = [
for (var i = 0; i < _channelCount; i++)
Channel(
index: i,
name: i == 0 ? 'Public' : '#topic-$i',
psk: Uint8List.fromList(List.filled(16, i + 1)),
unreadCount: i % 3 == 0 ? i : 0,
),
];
for (var i = 0; i < _channelCount; i++) {
connector.latest[i] = ChannelMessage(
senderName: 'Sender $i',
text: 'Message preview number $i on the mesh',
timestamp: now.subtract(Duration(minutes: i * 13)),
isOutgoing: false,
status: ChannelMessageStatus.sent,
channelIndex: i,
);
}
viewState.setChannelsSortOption(ChannelSortOption.name);
final animatedRows = await open(tester, const ChannelsScreen());
final list = find.byType(ListView);
expect(list, findsOneWidget);
counter.start();
final down = await _fling(
tester,
list,
connector,
offset: const Offset(0, -2500),
);
final flingBuilds = Map.of(counter.counts);
final flingTotal = counter.total;
counter.start();
await notifyAndSettle(tester);
final notifyTiles = counter['MeshCard'];
// ignore: avoid_print
print(
'[list-perf] channels fling: frames=${down.frames} '
'itemBuilds=${flingBuilds['ListEntrance'] ?? 0} '
'cardBuilds=${flingBuilds['MeshCard'] ?? 0} '
'allBuilds=$flingTotal '
'rowFramesNotFullyDrawn=${down.notFullyDrawnRowFrames} '
'maxRowsNotFullyDrawn=${down.maxNotFullyDrawn} '
'rowsNotFullyDrawnAtStop=${down.notFullyDrawnAfterStop}\n'
'[list-perf] channels notify (no change): cardBuilds=$notifyTiles',
);
expect(animatedRows, greaterThan(0));
expect(down.notFullyDrawnRowFrames, 0);
await close(tester);
});
}
+456
View File
@@ -0,0 +1,456 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/message.dart';
import 'package:meshcore_open/screens/channels_screen.dart';
import 'package:meshcore_open/screens/chat_screen.dart';
import 'package:meshcore_open/screens/contacts_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_filter/message_filter_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/channel_store.dart';
import 'package:meshcore_open/storage/contact_store.dart';
import 'package:meshcore_open/storage/last_radio_store.dart';
import 'package:meshcore_open/storage/message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/utils/contact_filter_types.dart';
final _radioKey = Uint8List.fromList(List<int>.generate(32, (i) => 0xA0 + i));
final _radioHex = pubKeyToHex(_radioKey);
Uint8List _key(int seed) =>
Uint8List.fromList(List<int>.generate(32, (i) => seed + i));
Uint8List _psk(int seed) =>
Uint8List.fromList(List<int>.generate(16, (i) => seed + i));
/// Local arrival times, an hour apart. Sender clocks are set far off them.
final _base = DateTime(2026, 11, 20, 12);
DateTime _arrived(int hours) => _base.add(Duration(hours: hours));
final _farFuture = DateTime(2099);
final _farPast = DateTime(2001);
ChannelMessage _channelMessage(
int slot,
String text, {
required DateTime sentAt,
required DateTime receivedAt,
String? filterReason,
}) => ChannelMessage(
senderName: 'Bob',
text: text,
timestamp: sentAt,
receivedAt: receivedAt,
isOutgoing: false,
status: ChannelMessageStatus.sent,
channelIndex: slot,
filterReason: filterReason,
);
Message _directMessage(
Uint8List senderKey,
String text, {
required DateTime sentAt,
required DateTime receivedAt,
}) => Message(
senderKey: senderKey,
text: text,
timestamp: sentAt,
receivedAt: receivedAt,
isOutgoing: false,
status: MessageStatus.delivered,
);
/// Seeds the remembered radio with channels (slots in map order) and
/// contacts, each with its saved messages.
Future<void> _seed({
Map<String, List<ChannelMessage> Function(int slot)> channelMessages =
const {},
Map<String, List<Message> Function(Uint8List key)> contactMessages = const {},
}) async {
final channelStore = ChannelStore()..setPublicKeyHex = _radioHex;
final messageStore = ChannelMessageStore()..setPublicKeyHex = _radioHex;
final channels = <Channel>[];
var slot = 0;
for (final entry in channelMessages.entries) {
final channel = Channel(index: slot, name: entry.key, psk: _psk(slot * 16));
channels.add(channel);
await messageStore.saveChannelMessages(
channel.storageId!,
entry.value(slot),
);
slot++;
}
await channelStore.saveChannels(channels);
await channelStore.saveSlotChannelIds({
for (final c in channels) c.index: c.storageId!,
});
final contacts = <Contact>[];
final directStore = MessageStore()..setPublicKeyHex = _radioHex;
var seed = 0x10;
for (final entry in contactMessages.entries) {
final key = _key(seed);
seed += 0x20;
final contact = Contact(
publicKey: key,
name: entry.key,
type: advTypeChat,
pathLength: 1,
path: Uint8List.fromList([0x22]),
lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000000),
);
contacts.add(contact);
await directStore.saveMessages(contact.publicKeyHex, entry.value(key));
}
await (ContactStore()..setPublicKeyHex = _radioHex).saveContacts(contacts);
await LastRadioStore().save(
LastRadio(
publicKeyHex: _radioHex,
name: 'Base',
transport: LastRadio.transportBle,
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
savedAt: DateTime.fromMillisecondsSinceEpoch(1700000000000),
),
);
ChannelMessageStore().forgetArchive();
MessageStore().forgetArchive();
}
/// Restores the seeded radio into a connector that never connects.
Future<MeshCoreConnector> _connector(
WidgetTester tester, {
MessageFilterService? filter,
}) async {
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
if (filter != null) {
final retry = MessageRetryService();
addTearDown(retry.dispose);
connector.initialize(
retryService: retry,
pathHistoryService: PathHistoryService(StorageService()),
messageFilterService: filter,
);
}
await tester.runAsync(connector.restoreLastRadio);
return connector;
}
Future<void> _pumpScreen(
WidgetTester tester,
MeshCoreConnector connector,
UiViewStateService viewState,
Widget home,
) async {
final storage = StorageService();
final settings = AppSettingsService();
await tester.runAsync(settings.loadSettings);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: MessageRetryService()),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: BleDebugLogService()),
ChangeNotifierProvider.value(value: AppDebugLogService()),
ChangeNotifierProvider.value(value: ChatTextScaleService()),
ChangeNotifierProvider.value(value: TranslationService(settings)),
ChangeNotifierProvider.value(value: viewState),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: ReceivedImageStore()),
ChangeNotifierProvider.value(
value: NetworkMapUploadService(
connector: connector,
settings: settings,
),
),
],
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: home,
),
),
);
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
/// [names] in the order they appear on screen, top to bottom.
List<String> _screenOrder(WidgetTester tester, List<String> names) {
final top = {
for (final name in names) name: tester.getTopLeft(find.text(name).first).dy,
};
return [...names]..sort((a, b) => top[a]!.compareTo(top[b]!));
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('recency_sort_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
ChannelMessageStore().forgetArchive();
MessageStore().forgetArchive();
});
Future<void> pumpChannels(
WidgetTester tester, {
MessageFilterService? filter,
}) async {
final connector = await _connector(tester, filter: filter);
final viewState = UiViewStateService()
..setChannelsSortOption(ChannelSortOption.latestMessages);
await _pumpScreen(tester, connector, viewState, const ChannelsScreen());
}
Future<void> pumpContacts(WidgetTester tester) async {
final connector = await _connector(tester);
final viewState = UiViewStateService()
..setContactsSortOption(ContactSortOption.recentMessages);
await _pumpScreen(tester, connector, viewState, const ContactsScreen());
}
testWidgets('Latest messages sorts channels by local arrival, not sender '
'clocks far in the future or past', (tester) async {
await _seed(
channelMessages: {
// Oldest arrival, but the sender's clock is decades ahead.
'Future Clock': (slot) => [
_channelMessage(
slot,
'from the future',
sentAt: _farFuture,
receivedAt: _arrived(0),
),
],
// Newest arrival, but the sender's clock is decades behind.
'Past Clock': (slot) => [
_channelMessage(
slot,
'from the past',
sentAt: _farPast,
receivedAt: _arrived(2),
),
],
'Correct Clock': (slot) => [
_channelMessage(
slot,
'on time',
sentAt: _arrived(1),
receivedAt: _arrived(1),
),
],
'Quiet': (_) => [],
},
);
await pumpChannels(tester);
expect(
_screenOrder(tester, [
'Future Clock',
'Past Clock',
'Correct Clock',
'Quiet',
]),
['Past Clock', 'Correct Clock', 'Future Clock', 'Quiet'],
);
await tester.pumpWidget(const SizedBox());
});
testWidgets('A newer message hidden by the message filter does not bump '
'its channel', (tester) async {
await _seed(
channelMessages: {
'Spammed': (slot) => [
_channelMessage(
slot,
'real message',
sentAt: _arrived(0),
receivedAt: _arrived(0),
),
_channelMessage(
slot,
'buy now',
sentAt: _farFuture,
receivedAt: _arrived(5),
filterReason: 'rule',
),
],
'Normal': (slot) => [
_channelMessage(
slot,
'hello',
sentAt: _arrived(1),
receivedAt: _arrived(1),
),
],
},
);
final filter = MessageFilterService();
addTearDown(filter.dispose);
await tester.runAsync(filter.load);
await pumpChannels(tester, filter: filter);
expect(_screenOrder(tester, ['Spammed', 'Normal']), ['Normal', 'Spammed']);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Channels with equal arrival times fall back to name order', (
tester,
) async {
List<ChannelMessage> same(int slot) => [
_channelMessage(slot, 'tie $slot', sentAt: _farFuture, receivedAt: _base),
];
await _seed(
channelMessages: {'Charlie': same, 'Alpha': same, 'Bravo': same},
);
await pumpChannels(tester);
expect(_screenOrder(tester, ['Charlie', 'Alpha', 'Bravo']), [
'Alpha',
'Bravo',
'Charlie',
]);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Recent messages sorts contacts by local arrival, not sender '
'clocks far in the future or past', (tester) async {
await _seed(
contactMessages: {
'Fiona': (key) => [
_directMessage(
key,
'from the future',
sentAt: _farFuture,
receivedAt: _arrived(0),
),
],
'Paul': (key) => [
_directMessage(
key,
'from the past',
sentAt: _farPast,
receivedAt: _arrived(2),
),
],
'Carl': (key) => [
_directMessage(
key,
'on time',
sentAt: _arrived(1),
receivedAt: _arrived(1),
),
],
},
);
await pumpContacts(tester);
expect(_screenOrder(tester, ['Fiona', 'Paul', 'Carl']), [
'Paul',
'Carl',
'Fiona',
]);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Contacts with equal arrival times fall back to name order', (
tester,
) async {
List<Message> same(Uint8List key) => [
_directMessage(key, 'tie', sentAt: _farPast, receivedAt: _base),
];
await _seed(contactMessages: {'Zed': same, 'Amy': same, 'Mo': same});
await pumpContacts(tester);
expect(_screenOrder(tester, ['Zed', 'Amy', 'Mo']), ['Amy', 'Mo', 'Zed']);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Contact rows still open after the list was replaced by an '
'empty search result', (tester) async {
List<Message> none(Uint8List key) => [];
await _seed(
contactMessages: {
'Amy': none,
'Ben': none,
'Cal': none,
'Dee': none,
'Eve': none,
},
);
final connector = await _connector(tester);
final viewState = UiViewStateService();
await _pumpScreen(tester, connector, viewState, const ContactsScreen());
expect(find.text('Amy'), findsOneWidget);
viewState.setContactsSearchText('no such contact');
await tester.pumpAndSettle();
expect(find.text('Amy'), findsNothing);
viewState.setContactsSearchText('');
await tester.pumpAndSettle();
await tester.longPress(find.text('Amy'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.byType(BottomSheet), findsOneWidget);
Navigator.of(tester.element(find.byType(BottomSheet))).pop();
await tester.pumpAndSettle();
await tester.tap(find.text('Amy'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.byType(ChatScreen), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
}
+26
View File
@@ -132,6 +132,32 @@ void main() {
},
);
test('keeps contact added times out of app settings', () async {
SharedPreferences.setMockInitialValues({
'app_settings': jsonEncode({'theme_mode': 'dark'}),
'contact_added_at_0011223344': jsonEncode({'aa': 1}),
});
PrefsManager.reset();
await PrefsManager.initialize();
addTearDown(PrefsManager.reset);
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
final json = await const BackupService().createBackup(
items: {BackupItem.appSettings},
connector: connector,
settings: AppSettings(),
password: '',
);
final payload = jsonDecode(json) as Map<String, dynamic>;
final section =
(payload['sections'] as Map<String, dynamic>)['appSettings']
as Map<String, dynamic>;
final preferences = section['preferences'] as Map<String, dynamic>;
expect(preferences, contains('app_settings'));
expect(preferences, isNot(contains('contact_added_at_0011223344')));
});
test('backs up a sensitive key without unrelated app settings', () async {
SharedPreferences.setMockInitialValues({
'app_settings': jsonEncode({
+73
View File
@@ -0,0 +1,73 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/l10n/app_localizations_en.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/widgets/contact_visuals.dart';
Contact _contact(int seed, {required DateTime lastSeen, DateTime? message}) =>
Contact(
publicKey: Uint8List.fromList(List.filled(32, seed)),
name: 'c$seed',
type: 1,
pathLength: -1,
path: Uint8List(0),
lastSeen: lastSeen,
lastMessageAt: message,
);
void main() {
final epoch = DateTime.fromMillisecondsSinceEpoch(0);
final now = DateTime.now();
test('added time orders a contact the radio has no advert time for', () {
final added = now.subtract(const Duration(minutes: 1));
final fromCard = _contact(1, lastSeen: epoch);
final heardHourAgo = _contact(
2,
lastSeen: now.subtract(const Duration(hours: 1)),
);
final addedAt = {fromCard: added};
final sorted = [heardHourAgo, fromCard]
..sort(
(a, b) => resolveContactLastSeen(
b,
addedAt: addedAt[b],
).compareTo(resolveContactLastSeen(a, addedAt: addedAt[a])),
);
expect(resolveContactLastSeen(fromCard, addedAt: added), added);
expect(sorted.first, fromCard);
});
test('a real advert time is never replaced by the added time', () {
final advert = now.subtract(const Duration(days: 30));
final contact = _contact(3, lastSeen: advert);
expect(resolveContactLastSeen(contact, addedAt: now), advert);
});
test('a newer message still wins over the added time', () {
final message = now;
final contact = _contact(4, lastSeen: epoch, message: message);
expect(
resolveContactLastSeen(
contact,
addedAt: now.subtract(const Duration(hours: 1)),
),
message,
);
});
test('a contact never heard shows "not heard yet", not decades ago', () {
final l10n = AppLocalizationsEn();
expect(formatContactLastSeen(l10n, epoch), l10n.contacts_lastSeenNever);
expect(
resolveContactLastSeen(_contact(5, lastSeen: epoch)),
epoch,
reason: 'display label is driven by the advert/message time only',
);
});
}