Fix review findings, add default flood scope, and address recent issues

Review fixes:
- Keep stored message history beyond the 200-message window; stop
  messages leaking between radios; reset link/session state on disconnect
- Accept firmware's 176-byte RX frames over USB/TCP
- Hold APP_START during contact sync; contact-sync watchdog; replay DMs
  from not-yet-known senders; tombstone late command replies; finish
  channel sync on ERR_NOT_FOUND; fail region-scoped sends cleanly
- DM retry watchdog when RESP_CODE_SENT never arrives; late repeater CLI
  replies; ACK hash collisions; UTF-8-safe name truncation
- Image pipeline: delete-during-decode, lifecycle cancels, decoder memory
  release, entry cap, dead worker recovery, atomic model writes
- Storage: deterministic reaction hash across web/native, Smaz
  double-decode, per-entry parsing, per-radio path history and regions,
  review-mode data isolation
- UI: safe channel slot selection, byte-length name limits, double-send
  guard, mounted checks, localized hardcoded strings
- Skip persisted-store reload on repeat SELF_INFO

Features:
- Radio default flood scope (firmware ver 11+) and explicit unscoped
  sends (ver 12+)
- Scan for nearby nodes (#570)
- Optional distinct first-hop repeater counting for channel resend (#589)
- Optional region next to hop count (#580)

Issues:
- Message text follows system font size (#569)
- Repeater/room password field accepts 20 chars (#576)
- TCP auto-reconnect and keepalive (#571)
- Order feeds by local receive time; flag future timestamps (#584)
- Coding rate help text (#568), French "Favoris" (#575)
- iOS/macOS app badge now clears

Translations for all new strings in every locale.
This commit is contained in:
zjs81 committed 2026-10-11 01:25:31 -07:00
1 parent a64a33d0c0
commit 25f197c979
120 files changed
+10424 -687

No files matched your search

@@ -0,0 +1,238 @@
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/connector/pending_command_replies.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/prefs_manager.dart';
import 'package:meshcore_open/storage/region_store.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));
}
}
/// Review radio that records every frame the app sends.
class _RecordingRadio extends ReviewRadio {
_RecordingRadio({required super.firmwareVerCode})
: super(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(milliseconds: 50),
replyDelay: const Duration(hours: 1),
);
final List<Uint8List> sent = [];
@override
void handle(Uint8List frame) {
sent.add(Uint8List.fromList(frame));
super.handle(frame);
}
Iterable<Uint8List> withCode(int code) =>
sent.where((f) => f.isNotEmpty && f[0] == code);
}
// NotificationService is a process-wide singleton whose reply stream can be
// listened to once, so every test shares one connector and reconnects it to a
// fresh radio.
late MeshCoreConnector _connector;
Future<(MeshCoreConnector, _RecordingRadio)> _connect(int verCode) async {
final connector = _connector;
final radio = _RecordingRadio(firmwareVerCode: verCode);
connector.reviewRadioFactoryForTest = () => radio;
await connector.connectReview();
addTearDown(connector.disconnect);
await _waitFor(
() => connector.firmwareVerCode == verCode && connector.channels.isNotEmpty,
);
// Let the version-gated config queries go out.
await Future<void>.delayed(const Duration(milliseconds: 200));
return (connector, radio);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
_connector = MeshCoreConnector();
final retryService = MessageRetryService();
_connector.initialize(
retryService: retryService,
pathHistoryService: PathHistoryService(StorageService()),
);
addTearDown(() {
_connector.dispose();
retryService.dispose();
});
});
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
group('frames', () {
test('SET_DEFAULT_FLOOD_SCOPE layout', () {
final frame = buildSetDefaultFloodScopeFrame('#eu-west');
expect(frame.length, 1 + 31 + 16);
expect(frame[0], cmdSetDefaultFloodScope);
expect(String.fromCharCodes(frame.sublist(1, 8)), 'eu-west');
expect(frame.sublist(8, 32).every((b) => b == 0), isTrue);
expect(frame.sublist(32), floodScopeKeyForRegion('eu-west'));
});
test('empty region clears the default', () {
expect(buildSetDefaultFloodScopeFrame(''), [cmdSetDefaultFloodScope]);
});
test('names of 31+ bytes are rejected', () {
expect(
() => buildSetDefaultFloodScopeFrame('a' * 31),
throwsArgumentError,
);
expect(buildSetDefaultFloodScopeFrame('a' * 30).length, 48);
});
test('DEFAULT_FLOOD_SCOPE reply parses name and key', () {
final set = buildSetDefaultFloodScopeFrame('eu');
final reply = Uint8List.fromList([
respCodeDefaultFloodScope,
...set.sublist(1),
]);
final parsed = parseDefaultFloodScopeFrame(reply)!;
expect(parsed.name, 'eu');
expect(parsed.key, floodScopeKeyForRegion('eu'));
});
test('empty or short DEFAULT_FLOOD_SCOPE reply means none', () {
expect(
parseDefaultFloodScopeFrame(
Uint8List.fromList([respCodeDefaultFloodScope]),
),
isNull,
);
expect(
parseDefaultFloodScopeFrame(
Uint8List.fromList([respCodeDefaultFloodScope, 0x65, 0x75]),
),
isNull,
);
});
test('explicit unscoped frame and reply mapping', () {
expect(buildSetFloodScopeUnscopedFrame(), [cmdSetFloodScope, 1]);
expect(
replyCodeForCommand(buildGetDefaultFloodScopeFrame()),
respCodeDefaultFloodScope,
);
expect(
replyCodeForCommand(buildSetDefaultFloodScopeFrame('eu')),
respCodeOk,
);
expect(
replyCodeForCommand(buildSetFloodScopeUnscopedFrame()),
respCodeOk,
);
});
});
group('version gating', () {
test('ver 10: no default scope query, "no region" sends plain', () async {
final (connector, radio) = await _connect(10);
expect(connector.supportsDefaultFloodScope, isFalse);
expect(connector.supportsExplicitUnscopedFlood, isFalse);
expect(radio.withCode(cmdGetDefaultFloodScope), isEmpty);
final channel = connector.channels.first;
await connector.setChannelRegion(channel.index, kUnscopedRegion);
await connector.sendChannelMessage(channel, 'hi');
expect(radio.withCode(cmdSetFloodScope), isEmpty);
});
test('ver 11: queries default but never sends [54,1]', () async {
final (connector, radio) = await _connect(11);
expect(connector.supportsDefaultFloodScope, isTrue);
expect(connector.supportsExplicitUnscopedFlood, isFalse);
expect(radio.withCode(cmdGetDefaultFloodScope), isNotEmpty);
await connector.setDefaultFloodScope('eu');
await _waitFor(() => connector.defaultFloodScopeName == 'eu');
final channel = connector.channels.first;
await connector.setChannelRegion(channel.index, kUnscopedRegion);
expect(connector.channelUsesRadioDefaultScope(channel.index), isTrue);
await connector.sendChannelMessage(channel, 'hi');
expect(radio.withCode(cmdSetFloodScope), isEmpty);
});
test(
'ver 14: "no region" forces unscoped, default follows radio',
() async {
final (connector, radio) = await _connect(14);
expect(connector.supportsExplicitUnscopedFlood, isTrue);
await connector.setDefaultFloodScope('eu');
await _waitFor(() => connector.defaultFloodScopeName == 'eu');
expect(connector.defaultFloodScopeKey, floodScopeKeyForRegion('eu'));
final channel = connector.channels.first;
// Following the default: no scope command, the radio default applies.
expect(connector.channelUsesRadioDefaultScope(channel.index), isTrue);
await connector.sendChannelMessage(channel, 'one');
expect(radio.withCode(cmdSetFloodScope), isEmpty);
// The stored label names the region the radio actually applied.
expect(connector.getChannelMessages(channel).last.region, 'eu');
// Explicit "no region": [54,1] around the send, then reset [54,0].
await connector.setChannelRegion(channel.index, kUnscopedRegion);
expect(connector.channelUsesRadioDefaultScope(channel.index), isFalse);
expect(connector.getEffectiveChannelRegion(channel.index), '');
await connector.sendChannelMessage(channel, 'two');
final scopeFrames = radio.withCode(cmdSetFloodScope).toList();
expect(scopeFrames.map((f) => f.toList()), [
[cmdSetFloodScope, 1],
[cmdSetFloodScope, 0],
]);
expect(
connector.getChannelMessages(channel).last.region,
anyOf(isNull, isEmpty),
);
// Clearing the radio default.
await connector.setDefaultFloodScope('');
await _waitFor(() => connector.defaultFloodScopeName == null);
},
);
test(
'app default "no region" applies to channels without their own',
() async {
final (connector, radio) = await _connect(14);
final channel = connector.channels.first;
await connector.setDefaultRegion(kUnscopedRegion);
await connector.sendChannelMessage(channel, 'hi');
expect(radio.withCode(cmdSetFloodScope).map((f) => f.toList()).first, [
cmdSetFloodScope,
1,
]);
// A channel's own region still wins over the app default.
await connector.setChannelRegion(channel.index, 'eu');
expect(connector.getEffectiveChannelRegion(channel.index), 'eu');
},
);
});
}
@@ -0,0 +1,69 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
void main() {
group('utf8BoundaryLength', () {
test('returns full length when it fits', () {
expect(utf8BoundaryLength(utf8.encode('abc'), 31), 3);
});
test('never splits a multi-byte character', () {
// 'é' is 2 bytes; 'a' + 15 × 'é' = 31 bytes, so 30 bytes cuts one.
final bytes = utf8.encode('a${'é' * 15}');
expect(utf8BoundaryLength(bytes, 30), 29);
expect(utf8BoundaryLength(bytes, 31), 31);
});
test('backs up over a 4-byte emoji', () {
final bytes = utf8.encode('ab😀');
expect(utf8BoundaryLength(bytes, 5), 2);
});
});
group('buildSetAdvertNameFrame', () {
test('truncates long names on a character boundary', () {
final name = 'Ж' * 20; // 40 bytes
final frame = buildSetAdvertNameFrame(name);
final nameBytes = frame.sublist(1);
expect(nameBytes.length, 30);
expect(utf8.decode(nameBytes), 'Ж' * 15);
});
test('keeps names shorter than the limit intact', () {
final frame = buildSetAdvertNameFrame('Node');
expect(utf8.decode(frame.sublist(1)), 'Node');
});
});
group('BufferWriter.writeCString', () {
test('NUL-terminates and truncates on a character boundary', () {
final writer = BufferWriter()..writeCString('#${'ё' * 20}', 32);
final bytes = writer.toBytes();
expect(bytes.length, 32);
final end = bytes.indexOf(0);
expect(utf8.decode(bytes.sublist(0, end)), '#${'ё' * 15}');
});
});
group('path hash width', () {
test('buildSendAnonReqFrame clamps width to 3', () {
final frame = buildSendAnonReqFrame(
Uint8List(32),
requestType: 1,
replyPath: Uint8List.fromList([1, 2, 3, 4, 5, 6]),
replyHopCount: 2,
pathHashWidth: 4,
);
final encodedPathLen = frame[1 + 32 + 1];
expect(encodedPathLen >> 6, 2); // width 3
expect(frame.sublist(1 + 32 + 2), [4, 5, 6, 1, 2, 3]);
});
test('buildSetPathHashModeFrame clamps mode to 2', () {
expect(buildSetPathHashModeFrame(3), [cmdSetPathHashMode, 0, 2]);
});
});
}
+206
View File
@@ -0,0 +1,206 @@
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/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/prefs_manager.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));
}
}
Uint8List _discoverResp({
required int type,
required int tag,
required List<int> key,
int snrQuarterDb = 20,
int remoteSnrQuarterDb = -8,
}) {
final tagBytes = ByteData(4)..setUint32(0, tag, Endian.little);
return Uint8List.fromList([
pushCodeControlData,
snrQuarterDb & 0xFF,
(-70) & 0xFF,
0,
(controlSubtypeDiscoverResp << 4) | type,
remoteSnrQuarterDb & 0xFF,
...tagBytes.buffer.asUint8List(),
...key,
]);
}
/// Review radio that records sent frames and can inject extra responses.
class _ScanRadio extends ReviewRadio {
_ScanRadio({required super.firmwareVerCode})
: super(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(milliseconds: 50),
replyDelay: const Duration(hours: 1),
);
final List<Uint8List> sent = [];
void Function(int tag)? onDiscoverRequest;
@override
void handle(Uint8List frame) {
sent.add(Uint8List.fromList(frame));
super.handle(frame);
if (frame.isNotEmpty && frame[0] == cmdSendControlData) {
final tag = ByteData.sublistView(frame, 3, 7).getUint32(0, Endian.little);
onDiscoverRequest?.call(tag);
}
}
}
late MeshCoreConnector _connector;
Future<(MeshCoreConnector, _ScanRadio)> _connect(int verCode) async {
final radio = _ScanRadio(firmwareVerCode: verCode);
_connector.reviewRadioFactoryForTest = () => radio;
await _connector.connectReview();
addTearDown(_connector.disconnect);
await _waitFor(
() =>
_connector.firmwareVerCode == verCode && _connector.channels.isNotEmpty,
);
return (_connector, radio);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
_connector = MeshCoreConnector();
final retryService = MessageRetryService();
_connector.initialize(
retryService: retryService,
pathHistoryService: PathHistoryService(StorageService()),
);
addTearDown(() {
_connector.dispose();
retryService.dispose();
});
});
group('frames', () {
test('scan request asks repeaters, rooms and sensors for full keys', () {
final payload = buildDiscoveryRequestPayload(
0x11223344,
typeMask: nodeDiscoverScanTypeMask,
);
expect(payload[0], 0x80); // DISCOVER_REQ, full keys
expect(payload[1], (1 << 2) | (1 << 3) | (1 << 4));
expect(
ByteData.sublistView(payload, 2, 6).getUint32(0, Endian.little),
0x11223344,
);
expect(payload.length, 10); // + since
expect(buildSendControlDataFrame(payload)[0], cmdSendControlData);
});
test('parses a full-key DISCOVER_RESP', () {
final key = List<int>.generate(32, (i) => i + 1);
final parsed = parseNodeDiscoverResponse(
_discoverResp(type: advTypeRepeater, tag: 0xDEADBEEF, key: key),
)!;
expect(parsed.nodeType, advTypeRepeater);
expect(parsed.tag, 0xDEADBEEF);
expect(parsed.snr, 5.0);
expect(parsed.remoteSnr, -2.0);
expect(parsed.rssi, -70);
expect(parsed.hasFullKey, isTrue);
expect(parsed.publicKey, key);
});
test('parses a prefix-only DISCOVER_RESP', () {
final parsed = parseNodeDiscoverResponse(
_discoverResp(type: advTypeSensor, tag: 1, key: List.filled(8, 0xAB)),
)!;
expect(parsed.hasFullKey, isFalse);
expect(parsed.publicKeyHex, 'ab' * 8);
});
test('rejects other control data and short frames', () {
final notResp = _discoverResp(
type: advTypeRepeater,
tag: 1,
key: List.filled(32, 1),
)..[4] = (controlSubtypeDiscoverReq << 4);
expect(parseNodeDiscoverResponse(notResp), isNull);
expect(
parseNodeDiscoverResponse(
_discoverResp(type: advTypeRepeater, tag: 1, key: [1, 2, 3]),
),
isNull,
);
expect(parseNodeDiscoverResponse(Uint8List.fromList([0x80])), isNull);
});
});
group('connector', () {
test(
'collects tagged responses, ignoring other tags and duplicates',
() async {
final (connector, radio) = await _connect(14);
expect(connector.supportsNodeDiscover, isTrue);
final stranger = List<int>.generate(32, (i) => 0xF0 ^ i);
radio.onDiscoverRequest = (tag) {
// A reply to someone else's scan, then a stranger answering twice.
radio.emitForTest(
_discoverResp(type: advTypeRepeater, tag: tag ^ 1, key: stranger),
);
radio.emitForTest(
_discoverResp(type: advTypeSensor, tag: tag, key: stranger),
);
radio.emitForTest(
_discoverResp(type: advTypeSensor, tag: tag, key: stranger),
);
};
final results = await connector
.discoverNearbyNodes(timeout: const Duration(milliseconds: 600))
.toList();
final keys = results.map((r) => r.publicKeyHex).toList();
expect(keys.toSet().length, keys.length, reason: 'no duplicates');
expect(keys, contains(pubKeyToHex(Uint8List.fromList(stranger))));
// The scripted Hilltop Repeater answers too, and is a known contact.
final repeater = results.firstWhere(
(r) => r.nodeType == advTypeRepeater,
);
expect(
connector.contactForDiscoverResponse(repeater).name,
'Hilltop Repeater',
);
// An unknown node gets a direct-path placeholder named by its key.
final unknown = connector.contactForDiscoverResponse(
results.firstWhere((r) => r.nodeType == advTypeSensor),
);
expect(unknown.pathLength, 0);
expect(unknown.name, 'F0F1F2F3');
},
);
test('older firmware gets no scan request', () async {
final (connector, radio) = await _connect(7);
expect(connector.supportsNodeDiscover, isFalse);
final results = await connector
.discoverNearbyNodes(timeout: const Duration(milliseconds: 200))
.toList();
expect(results, isEmpty);
expect(radio.sent.where((f) => f[0] == cmdSendControlData), isEmpty);
});
});
}
@@ -67,4 +67,52 @@ void main() {
queue.takeErr(6);
await expectLater(pending!.completer!.future, throwsException);
});
group('timed-out entries', () {
late DateTime now;
PendingCommandReplies clockedQueue() => PendingCommandReplies(
staleAfter: const Duration(seconds: 10),
tombstoneLifetime: const Duration(seconds: 5),
clock: () => now,
);
setUp(() => now = DateTime(2026, 1, 1));
test('late OK is absorbed instead of completing the next command', () {
final queue = clockedQueue();
final scope = queue.track(
buildSetFloodScopeFrame(''),
waitForReply: true,
);
final text = queue.track(
buildSendChannelTextMsgFrame(0, 'hi'),
channelSendQueueId: 'msg-1',
);
queue.markTimedOut(scope!);
expect(queue.takeOk(), isNull); // the late OK for SET_FLOOD_SCOPE
expect(queue.takeOk(), same(text));
expect(queue.length, 0);
});
test('late ERR is absorbed by the oldest timed-out entry', () {
final queue = clockedQueue();
final first = queue.track(buildSetDeviceTimeFrame(1), waitForReply: true);
final second = queue.track(buildSetAdvertNameFrame('x'));
queue.markTimedOut(first!);
expect(queue.takeErr(2), isNull);
expect(queue.takeErr(2), same(second));
});
test('a timed-out entry expires after its lifetime', () {
final queue = clockedQueue();
final first = queue.track(buildSetDeviceTimeFrame(1), waitForReply: true);
queue.markTimedOut(first!);
now = now.add(const Duration(seconds: 6));
final next = queue.track(buildSetAdvertNameFrame('x'));
expect(queue.takeOk(), same(next));
});
});
}
+210
View File
@@ -0,0 +1,210 @@
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.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/services/usb_serial_frame_codec.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<void> _waitFor(bool Function() condition, {int seconds = 10}) 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));
}
}
/// A companion reachable over loopback TCP: each accepted socket gets its own
/// [ReviewRadio] answering the app's frames with the serial framing.
class _FakeTcpCompanion {
late final ServerSocket _server;
final List<Socket> _clients = [];
final List<ReviewRadio> _radios = [];
int accepted = 0;
int get port => _server.port;
Future<void> start() async {
_server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
_server.listen((socket) {
accepted += 1;
_clients.add(socket);
// Writes after the app hangs up fail with a broken pipe; that is
// expected here and must not fail the test.
var closed = false;
unawaited(
socket.done.catchError((_) {}).whenComplete(() => closed = true),
);
final radio = ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
replyDelay: const Duration(hours: 1),
);
_radios.add(radio);
radio.frames.listen((payload) {
if (closed) return;
final length = payload.length;
try {
socket.add([
usbSerialRxFrameStart,
length & 0xFF,
(length >> 8) & 0xFF,
...payload,
]);
} catch (_) {}
});
final decoder = UsbSerialFrameDecoder();
socket.listen(
(bytes) {
for (final packet in decoder.ingest(Uint8List.fromList(bytes))) {
radio.handle(packet.payload);
}
},
onError: (_) {},
onDone: () => closed = true,
cancelOnError: true,
);
});
}
/// Simulates the link dying under the app (e.g. Wi-Fi power saving).
void dropClients() {
for (final socket in _clients) {
socket.destroy();
}
_clients.clear();
}
Future<void> close() async {
dropClients();
for (final radio in _radios) {
radio.dispose();
}
await _server.close();
}
}
// NotificationService is a process-wide singleton whose reply stream can be
// listened to once, so every test shares one connector.
late MeshCoreConnector _connector;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
_connector = MeshCoreConnector();
final retryService = MessageRetryService();
_connector.initialize(
retryService: retryService,
pathHistoryService: PathHistoryService(StorageService()),
);
addTearDown(() {
_connector.dispose();
retryService.dispose();
});
});
tearDown(() async {
await _connector.disconnect();
});
test('a dropped TCP link reconnects to the same endpoint', () async {
final companion = _FakeTcpCompanion();
await companion.start();
addTearDown(companion.close);
await _connector.connectTcp(
host: InternetAddress.loopbackIPv4.address,
port: companion.port,
);
expect(_connector.isTcpTransportConnected, isTrue);
expect(companion.accepted, 1);
companion.dropClients();
await _waitFor(
() => _connector.state == MeshCoreConnectionState.disconnected,
);
expect(_connector.isAutoReconnectScheduled, isTrue);
// Wait for the reconnect's handshake to finish (SELF_INFO), not just the
// socket, so tearDown does not race a half-finished attempt.
await _waitFor(
() =>
companion.accepted == 2 &&
_connector.isTcpTransportConnected &&
_connector.selfPublicKey != null,
);
await Future<void>.delayed(const Duration(milliseconds: 300));
expect(
_connector.activeTcpEndpoint,
'${InternetAddress.loopbackIPv4.address}:${companion.port}',
);
});
test('a manual disconnect does not reconnect', () async {
final companion = _FakeTcpCompanion();
await companion.start();
addTearDown(companion.close);
await _connector.connectTcp(
host: InternetAddress.loopbackIPv4.address,
port: companion.port,
);
expect(_connector.isTcpTransportConnected, isTrue);
await _connector.disconnect();
expect(_connector.isAutoReconnectScheduled, isFalse);
await Future<void>.delayed(const Duration(milliseconds: 1500));
expect(companion.accepted, 1);
expect(_connector.state, MeshCoreConnectionState.disconnected);
});
test('a first connect that fails does not start reconnecting', () async {
final unused = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = unused.port;
await unused.close();
await expectLater(
_connector.connectTcp(
host: InternetAddress.loopbackIPv4.address,
port: port,
),
throwsA(anything),
);
expect(_connector.state, MeshCoreConnectionState.disconnected);
expect(_connector.isAutoReconnectScheduled, isFalse);
});
test(
'reconnect keeps retrying with backoff while the endpoint is down',
() async {
final companion = _FakeTcpCompanion();
await companion.start();
final port = companion.port;
await _connector.connectTcp(
host: InternetAddress.loopbackIPv4.address,
port: port,
);
expect(_connector.isTcpTransportConnected, isTrue);
// The companion goes away entirely: attempts fail and are rescheduled.
await companion.close();
await _waitFor(
() => _connector.state == MeshCoreConnectionState.disconnected,
);
await Future<void>.delayed(const Duration(milliseconds: 1500));
expect(_connector.isTcpTransportConnected, isFalse);
expect(_connector.isAutoReconnectScheduled, isTrue);
},
);
}
@@ -0,0 +1,142 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/channel_resend_coverage.dart';
import 'package:meshcore_open/models/app_settings.dart';
import 'package:meshcore_open/models/channel_message.dart';
ChannelMessage _echoed(
List<List<int>> paths, {
int width = 1,
int? pathLength,
}) {
final variants = [for (final p in paths) Uint8List.fromList(p)];
return ChannelMessage(
senderName: 'me',
text: 'hello',
timestamp: DateTime(2026, 10, 11),
isOutgoing: true,
pathHashWidth: width,
pathLength:
pathLength ??
variants.fold<int>(
0,
(m, p) => p.length ~/ width > m ? p.length ~/ width : m,
),
pathBytes: variants.isEmpty ? null : variants.first,
pathVariants: variants,
);
}
void main() {
group('channelResendSatisfied', () {
test('two distinct first-hop repeaters satisfy N=2 only when on', () {
final message = _echoed([
[0xAA],
[0xBB],
]);
expect(
channelResendSatisfied(
message,
minHops: 2,
countDistinctRepeaters: false,
),
isFalse,
);
expect(
channelResendSatisfied(
message,
minHops: 2,
countDistinctRepeaters: true,
),
isTrue,
);
});
test('the same repeater heard twice does not count twice', () {
final message = _echoed([
[0xAA],
[0xAA],
]);
expect(distinctFirstHopRepeaters(message), {'aa'});
expect(
channelResendSatisfied(
message,
minHops: 2,
countDistinctRepeaters: true,
),
isFalse,
);
});
test('consecutive hops still satisfy with the toggle off', () {
final message = _echoed([
[0xAA, 0xCC],
]);
expect(
channelResendSatisfied(
message,
minHops: 2,
countDistinctRepeaters: false,
),
isTrue,
);
});
test('first hop uses the path hash width', () {
// Same first byte, different 2-byte hashes: two distinct repeaters.
final message = _echoed([
[0xAA, 0x01],
[0xAA, 0x02],
], width: 2);
expect(distinctFirstHopRepeaters(message), {'aa01', 'aa02'});
});
test('our own key prefix and zero-hop echoes are ignored', () {
final self = Uint8List.fromList(List.filled(32, 0x11));
final message = _echoed([
[0x11],
[0xAA],
[],
], pathLength: 1);
expect(distinctFirstHopRepeaters(message, selfPublicKey: self), {'aa'});
expect(
channelResendSatisfied(
message,
minHops: 2,
countDistinctRepeaters: true,
selfPublicKey: self,
),
isFalse,
);
});
test('an unechoed message is not satisfied', () {
final message = _echoed([]);
expect(
channelResendSatisfied(
message,
minHops: 1,
countDistinctRepeaters: true,
),
isFalse,
);
});
});
group('channelMinHopsCountRepeaters setting', () {
test('defaults off, including for old saved settings', () {
expect(AppSettings().channelMinHopsCountRepeaters, isFalse);
expect(AppSettings.fromJson({}).channelMinHopsCountRepeaters, isFalse);
});
test('round-trips through JSON and copyWith', () {
final on = AppSettings().copyWith(channelMinHopsCountRepeaters: true);
expect(on.channelMinHopsCountRepeaters, isTrue);
expect(
AppSettings.fromJson(on.toJson()).channelMinHopsCountRepeaters,
isTrue,
);
});
});
}
@@ -72,4 +72,29 @@ void main() {
);
expect(result.text, 'abcdef');
});
test('truncateUtf8 never splits a multi-byte character', () {
// 'й' is 2 bytes; 31 bytes would land mid-character.
final name = 'й' * 20;
final cut = truncateUtf8(name, maxRadioNameBytes);
expect(utf8ByteLength(cut), 30);
expect(cut, 'й' * 15);
expect(truncateUtf8('short', maxRadioNameBytes), 'short');
});
test('fitRadioName keeps the suffix and fits the radio field', () {
final fitted = fitRadioName('A' * 40, 'Public');
expect(fitted.endsWith(' Public'), isTrue);
expect(utf8ByteLength(fitted), maxRadioNameBytes);
expect(fitRadioName('Hikers', 'Public'), 'Hikers Public');
});
test('encoder counts a hashtag prefix toward the byte limit', () {
final formatter = Utf8LengthLimitingTextInputFormatter(
maxRadioNameBytes,
encoder: (text) => '#$text',
);
final result = formatter.formatEditUpdate(_value(''), _value('a' * 40));
expect(result.text, 'a' * 30);
});
}
+217
View File
@@ -0,0 +1,217 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/reaction_helper.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/message.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _device = 'abcdef012345';
const _contact = 'c1';
Future<void> _init([Map<String, Object> values = const {}]) async {
SharedPreferences.setMockInitialValues(values);
PrefsManager.reset();
await PrefsManager.initialize();
MessageStore().forgetArchive();
ChannelMessageStore().forgetArchive();
}
ChannelMessage _ch(
String text, {
required DateTime timestamp,
DateTime? receivedAt,
}) => ChannelMessage(
senderKey: null,
senderName: 'Bob',
text: text,
timestamp: timestamp,
receivedAt: receivedAt,
isOutgoing: false,
status: ChannelMessageStatus.sent,
channelIndex: 0,
);
void main() {
final base = DateTime(2026, 10, 1, 12);
group('receivedAt model', () {
test('defaults to the sender timestamp and survives copyWith', () {
final dm = Message(
senderKey: Uint8List.fromList([1, 2, 3]),
text: 'hi',
timestamp: base,
isOutgoing: false,
);
expect(dm.receivedAt, base);
final later = base.add(const Duration(minutes: 3));
final ch = _ch('hi', timestamp: base, receivedAt: later);
expect(ch.copyWith(repeatCount: 2).receivedAt, later);
final dm2 = Message(
senderKey: Uint8List.fromList([1]),
text: 'x',
timestamp: base,
receivedAt: later,
isOutgoing: false,
);
expect(dm2.copyWith(retryCount: 1).receivedAt, later);
});
test('flags timestamps well ahead of arrival only', () {
expect(
_ch(
'a',
timestamp: base.add(const Duration(hours: 1)),
receivedAt: base,
).hasFutureTimestamp,
isTrue,
);
expect(
_ch(
'b',
timestamp: base.add(const Duration(minutes: 2)),
receivedAt: base,
).hasFutureTimestamp,
isFalse,
);
expect(
_ch(
'c',
timestamp: base.subtract(const Duration(days: 1)),
receivedAt: base,
).hasFutureTimestamp,
isFalse,
);
});
test('identity (messageId, reaction hash) ignores receivedAt', () {
final a = _ch('hello there', timestamp: base, receivedAt: base);
final b = _ch(
'hello there',
timestamp: base,
receivedAt: base.add(const Duration(hours: 5)),
);
expect(a.messageId, b.messageId);
final secs = base.millisecondsSinceEpoch ~/ 1000;
final hash = ReactionHelper.computeReactionHash(
secs,
'Bob',
'hello there',
);
final info = ReactionHelper.parseReaction(
ReactionHelper.encodeReaction(hash, '00'),
)!;
final messages = [b];
final matched = ReactionHelper.applyReaction<ChannelMessage>(
messages: messages,
reactionInfo: info,
getTimestampSecs: (m) => m.timestamp.millisecondsSinceEpoch ~/ 1000,
getSenderName: (m) => m.senderName,
getMessageText: (m) => m.text,
getReactions: (m) => m.reactions,
shouldSkip: (_) => false,
updateMessage: (int i, Map<String, List<String?>> reactions) {},
);
expect(matched, isTrue);
});
});
group('receivedAt persistence', () {
test('channel store round-trips receivedAt', () async {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _device;
final received = base.add(const Duration(seconds: 42));
await store.saveChannelMessages(0, [
_ch('one', timestamp: base, receivedAt: received),
]);
final loaded = await store.loadChannelMessages(0);
expect(loaded.single.receivedAt, received);
expect(loaded.single.timestamp, base);
});
test('DM store round-trips receivedAt', () async {
await _init();
final store = MessageStore()..setPublicKeyHex = _device;
final received = base.add(const Duration(seconds: 7));
await store.saveMessages(_contact, [
Message(
senderKey: Uint8List.fromList([1, 2, 3]),
text: 'hi',
timestamp: base,
receivedAt: received,
isOutgoing: false,
status: MessageStatus.delivered,
messageId: 'id1',
),
]);
final loaded = await store.loadMessages(_contact);
expect(loaded.single.receivedAt, received);
});
test('legacy records fall back to the timestamp, capped at now', () async {
final past = DateTime.now().subtract(const Duration(days: 2));
final future = DateTime.now().add(const Duration(days: 1));
Map<String, Object?> record(String text, DateTime ts) => {
'senderName': 'Bob',
'text': text,
'timestamp': ts.millisecondsSinceEpoch,
'isOutgoing': false,
'status': ChannelMessageStatus.sent.index,
'messageId': 'legacy-$text',
'plainText': true,
};
await _init({
'channel_messages_${_device.substring(0, 10)}0': jsonEncode([
record('old', past),
record('ahead', future),
]),
});
final store = ChannelMessageStore()..setPublicKeyHex = _device;
final before = DateTime.now();
final loaded = await store.loadChannelMessages(0);
expect(loaded, hasLength(2));
expect(
loaded[0].receivedAt.millisecondsSinceEpoch,
past.millisecondsSinceEpoch,
);
// A stored future-dated message no longer sorts below later arrivals.
expect(loaded[1].receivedAt.isAfter(future), isFalse);
expect(
loaded[1].receivedAt.isBefore(
before.subtract(const Duration(seconds: 1)),
),
isFalse,
);
expect(loaded[1].hasFutureTimestamp, isTrue);
});
});
test(
'ordering by receivedAt keeps a future-dated message in arrival order',
() {
final early = _ch(
'clock ahead',
timestamp: base.add(const Duration(days: 1)),
receivedAt: base,
);
final late = _ch(
'normal',
timestamp: base.add(const Duration(minutes: 10)),
receivedAt: base.add(const Duration(minutes: 10)),
);
final byTimestamp = [late, early]
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
expect(byTimestamp.last.text, 'clock ahead');
final byArrival = [late, early]
..sort((a, b) => a.receivedAt.compareTo(b.receivedAt));
expect(byArrival.map((m) => m.text), ['clock ahead', 'normal']);
},
);
}
+21
View File
@@ -0,0 +1,21 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/app_settings.dart';
void main() {
group('AppSettings.regionOnHopsLine', () {
test('defaults to off, including for stored settings without the key', () {
expect(AppSettings().regionOnHopsLine, isFalse);
final legacy = AppSettings().toJson()..remove('region_on_hops_line');
expect(AppSettings.fromJson(legacy).regionOnHopsLine, isFalse);
});
test('round-trips through JSON and survives copyWith', () {
final enabled = AppSettings().copyWith(regionOnHopsLine: true);
expect(AppSettings.fromJson(enabled.toJson()).regionOnHopsLine, isTrue);
expect(
enabled.copyWith(enableMessageTracing: true).regionOnHopsLine,
isTrue,
);
});
});
}
+35
View File
@@ -131,6 +131,41 @@ void main() {
expect(hash, matches(RegExp(r'^[0-9a-f]{4}$')));
});
test('matches legacy native (Dart VM String.hashCode) vectors', () {
// Values produced by `String.hashCode & 0xFFFF` on the Dart VM, which
// existing native clients send. Web builds must compute the same.
expect(
ReactionHelper.computeReactionHash(1700000000, 'Bob', 'hello'),
'e779',
);
expect(
ReactionHelper.computeReactionHash(1700000000, null, 'hi'),
'b5bd',
);
expect(
ReactionHelper.computeReactionHash(1700000000, 'Привет😀', 'x'),
'7fee',
);
});
test('stableStringHash equals VM String.hashCode', () {
// Only meaningful on the VM, where the test suite runs.
for (final input in [
'',
'a',
'1234567890AliceHello',
'Привет мир',
'😀🎉 emoji',
'x' * 300,
]) {
expect(
ReactionHelper.stableStringHash(input),
input.hashCode,
reason: input,
);
}
});
test('should be deterministic', () {
final hash1 = ReactionHelper.computeReactionHash(
1234567890,
@@ -0,0 +1,95 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/message.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
Contact _contact() => Contact(
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => 0xAA + i)),
name: 'Test',
type: 1,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.now(),
);
void main() {
late MessageRetryService service;
late Map<String, Message> latest;
late List<({int attempt, int timestamp})> sends;
late int timeoutMs;
final selfKey = Uint8List(32);
setUp(() {
service = MessageRetryService(
sentWatchdogGrace: const Duration(milliseconds: 10),
);
latest = {};
sends = [];
timeoutMs = 20;
service.initialize(
RetryServiceConfig(
sendMessage: (_, _, attempt, timestamp) async {
sends.add((attempt: attempt, timestamp: timestamp));
},
addMessage: (_, m) => latest[m.messageId] = m,
updateMessage: (m) => latest[m.messageId] = m,
getSelfPublicKey: () => selfKey,
calculateTimeout: (_, _, {String? contactKey, int? deviceTimeoutMs}) =>
timeoutMs,
),
);
});
tearDown(() => service.dispose());
int ackHashFor(int attempt) => MessageRetryService.computeExpectedAckHash(
sends.first.timestamp,
attempt,
'hello',
selfKey,
);
test('missing RESP_CODE_SENT times out and retries', () async {
await service.sendMessageWithRetry(contact: _contact(), text: 'hello');
await pumpEventQueue();
expect(sends.map((s) => s.attempt), [0]);
// Watchdog (20ms + 10ms grace) fires, then the 1s retry backoff.
await Future<void>.delayed(const Duration(milliseconds: 1200));
expect(sends.map((s) => s.attempt), [0, 1]);
});
test('RESP_CODE_SENT replaces the watchdog without a double retry', () async {
await service.sendMessageWithRetry(contact: _contact(), text: 'hello');
await pumpEventQueue();
timeoutMs = 60000;
expect(service.updateMessageFromSent(ackHashFor(0), 0), isTrue);
await Future<void>.delayed(const Duration(milliseconds: 200));
expect(sends, hasLength(1));
expect(latest.values.single.status, MessageStatus.sent);
});
test('late ACK for an attempt whose SENT was lost still delivers', () async {
await service.sendMessageWithRetry(contact: _contact(), text: 'hello');
await pumpEventQueue();
// Let the watchdog fire; the retry is now waiting on its backoff.
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(latest.values.single.retryCount, 1);
service.handleAckReceived(ackHashFor(0), 500);
expect(latest.values.single.status, MessageStatus.delivered);
expect(service.hasPendingMessages, isFalse);
// The cancelled backoff must not resend.
await Future<void>.delayed(const Duration(milliseconds: 1100));
expect(sends, hasLength(1));
});
}
@@ -114,6 +114,7 @@ typedef _Rig = ({
_Rig _build({
int burstCap = 3,
int maxImages = 200,
int maxEntries = 400,
int maxBytes = 64 * 1024 * 1024,
Duration maxAge = const Duration(days: 30),
_FakeDecoder? decoder,
@@ -130,6 +131,7 @@ _Rig _build({
processAutomatically: processAutomatically,
burstCap: burstCap,
maxImages: maxImages,
maxEntries: maxEntries,
maxBytes: maxBytes,
maxAge: maxAge,
clock: () => now,
@@ -1283,6 +1285,154 @@ void main() {
expect(after.needsManualDecode, isTrue);
});
});
group('review fixes 2026-10-11', () {
Future<void> waitForState(
_Rig h,
String id,
ReceivedImageState state,
) async {
for (var i = 0; i < 200; i++) {
if (h.store.entryFor(id)?.state == state) return;
await Future<void>.delayed(const Duration(milliseconds: 1));
}
fail('never reached $state');
}
test('deleting an image mid-decode does not bring it back', () async {
final decoder = _FakeDecoder()..delay = const Duration(milliseconds: 30);
final h = _build(decoder: decoder);
final entry = await _completeOne(h);
await waitForState(h, entry.streamId, ReceivedImageState.decoding);
await h.store.deleteImage(entry.streamId);
await h.store.settle();
await Future<void>.delayed(const Duration(milliseconds: 60));
expect(h.store.entryFor(entry.streamId), isNull);
expect(h.blobs.hasPng(entry.streamId), isFalse);
expect(h.blobs.hasSidecar(entry.streamId), isFalse);
});
test('backgrounding mid-decode re-queues instead of failing', () async {
final decoder = _FakeDecoder(mode: 'fail')
..delay = const Duration(milliseconds: 30);
final h = _build(decoder: decoder);
final entry = await _completeOne(h);
await waitForState(h, entry.streamId, ReceivedImageState.decoding);
h.store.setForeground(false);
expect(decoder.cancels, 1);
await Future<void>.delayed(const Duration(milliseconds: 60));
await h.store.settle();
final parked = h.store.entryFor(entry.streamId)!;
expect(parked.state, ReceivedImageState.reassembled);
expect(parked.needsManualDecode, isFalse);
expect(h.store.decodeQueue, contains(entry.streamId));
decoder.mode = 'ok';
h.store.setForeground(true);
await h.store.settle();
expect(
h.store.entryFor(entry.streamId)!.state,
ReceivedImageState.decoded,
);
});
test('backgrounding with no decode running cancels nothing', () async {
final h = _build();
h.store.setForeground(false);
expect(h.decoder.cancels, 0);
});
test('undecoded entries are capped by maxEntries, oldest first', () async {
final h = _build(processAutomatically: false, maxEntries: 3);
final ids = <String>[];
for (var i = 0; i < 5; i++) {
ids.add((await _completeOne(h, imgId: 40 + i, seed: i)).streamId);
h.advance(const Duration(seconds: 2));
}
expect(h.store.entries.length, 3);
expect(h.store.entryFor(ids[0]), isNull);
expect(h.store.entryFor(ids[1]), isNull);
expect(h.store.entryFor(ids[4]), isNotNull);
expect(h.blobs.hasBitstream(ids[0]), isFalse);
});
test(
'deleting an old image keeps a newer stream on the same key',
() async {
final h = _build();
final old = await _completeOne(h, imgId: 5);
await h.store.settle();
h.advance(const Duration(seconds: 5));
// A newer two-chunk image reusing the same 8-bit id starts arriving.
final set = buildImageChunks(
payload: _payload(kImageChunkFirstCapacity + 1, 9),
metadata: const ImageStreamMetadata(
rate: ImageCodecRatePoint.standard,
),
senderPrefix: kSender,
imgId: 5,
);
final newer = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[0], channelIndex: 3, now: h.clock()),
channelIndex: 3,
at: h.clock(),
);
expect(newer!.state, ReceivedImageState.receiving);
final key = newer.key;
expect(h.store.entryForKey(key)!.streamId, newer.streamId);
await h.store.deleteImage(old.streamId);
expect(h.store.entryForKey(key)!.streamId, newer.streamId);
final done = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[1], channelIndex: 3, now: h.clock()),
channelIndex: 3,
at: h.clock(),
);
expect(done!.streamId, newer.streamId);
},
);
test('a reserved high-rate stream is unsupported, not retryable', () async {
final h = _build();
final set = buildImageChunks(
payload: _payload(140),
metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.high),
senderPrefix: kSender,
imgId: 12,
);
final entry = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[0], channelIndex: 3, now: h.clock()),
channelIndex: 3,
at: h.clock(),
);
expect(entry!.state, ReceivedImageState.failedCorrupt);
expect(entry.canRetryDecode, isFalse);
expect(h.blobs.hasBitstream(entry.streamId), isFalse);
await h.store.settle();
expect(h.decoder.calls, 0);
});
test('outgoing entries keep their aspect code', () async {
final h = _build();
final entry = await h.store.registerOutgoing(
channelIndex: 1,
senderPrefix: kSelf,
imgId: 3,
previewPng: Uint8List.fromList(List<int>.filled(10, 1)),
rate: AeicRatePoint.ft32,
chunkCount: 1,
aspectCode: 2,
);
expect(entry.aspectCode, 2);
expect(entry.displayAspectRatio, closeTo(4 / 3, 0.001));
});
});
}
/// Delivers a whole single-chunk image and returns its entry (state
@@ -21,6 +21,28 @@ class _FakeConnector extends MeshCoreConnector {
}) async {}
}
class _ShortTimeoutConnector extends _FakeConnector {
final List<Uint8List> sentFrames = [];
@override
int calculateTimeout({
required int pathLength,
int messageBytes = 100,
String? contactKey,
int? deviceTimeoutMs,
}) => 30;
@override
Future<void> sendFrame(
Uint8List data, {
String? channelSendQueueId,
bool expectsGenericAck = false,
bool waitForGenericAck = false,
}) async {
sentFrames.add(data);
}
}
Contact _repeater(int seed) => Contact(
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => seed + i)),
name: 'R$seed',
@@ -118,4 +140,63 @@ void main() {
expect(result, 'unprefixed');
});
});
group('RepeaterCommandService retries', () {
test('late reply to an earlier attempt completes the command', () async {
final connector = _ShortTimeoutConnector();
final service = RepeaterCommandService(connector);
addTearDown(service.dispose);
final repeater = _repeater(1);
String? result;
unawaited(
service
.sendCommand(repeater, 'password x', retries: 3)
.then((r) => result = r, onError: (_) {}),
);
// Attempt 1 (00|) times out after 30ms and attempt 2 (01|) is sent.
await Future<void>.delayed(const Duration(milliseconds: 45));
expect(connector.sentFrames, hasLength(2));
service.handleResponse(repeater, '00|OK');
await pumpEventQueue();
expect(result, 'OK');
// No third attempt goes out once the call has completed.
await Future<void>.delayed(const Duration(milliseconds: 60));
expect(connector.sentFrames, hasLength(2));
});
test('prefixes are released once the command finishes', () async {
final connector = _ShortTimeoutConnector();
final service = RepeaterCommandService(connector);
addTearDown(service.dispose);
final repeater = _repeater(1);
Object? error;
await service.sendCommand(repeater, 'ver', retries: 2).catchError((
Object e,
) {
error = e;
return '';
});
expect(error, isNotNull);
String? result;
unawaited(
service
.sendCommand(repeater, 'ver', retries: 1)
.then((r) => result = r, onError: (_) {}),
);
await pumpEventQueue();
// Replies to the finished call's prefixes are ignored.
service.handleResponse(repeater, '00|stale');
service.handleResponse(repeater, '01|stale');
await pumpEventQueue();
expect(result, isNull);
service.handleResponse(repeater, '02|fresh');
await pumpEventQueue();
expect(result, 'fresh');
});
});
}
@@ -30,7 +30,66 @@ final class _DelayedConnectOverrides extends IOOverrides {
}
}
final class _CapturingConnectOverrides extends IOOverrides {
Socket? socket;
@override
Future<Socket> socketConnect(
host,
int port, {
sourceAddress,
int sourcePort = 0,
Duration? timeout,
}) async {
final connected = await super.socketConnect(
host,
port,
sourceAddress: sourceAddress,
sourcePort: sourcePort,
timeout: timeout,
);
socket = connected;
return connected;
}
}
int _readIntOption(Socket socket, int level, int option) {
final value = socket.getRawOption(
RawSocketOption(level, option, Uint8List(4)),
);
return ByteData.sublistView(value).getInt32(0, Endian.host);
}
void main() {
test(
'connect enables TCP keepalive with short probe timings',
() async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final overrides = _CapturingConnectOverrides();
final service = TcpTransportService();
try {
await IOOverrides.runZoned(
() => service.connect(
host: InternetAddress.loopbackIPv4.address,
port: server.port,
),
socketConnect: overrides.socketConnect,
);
final socket = overrides.socket!;
// Linux values: SO_KEEPALIVE 9, TCP_KEEPIDLE 4, TCP_KEEPINTVL 5,
// TCP_KEEPCNT 6.
expect(_readIntOption(socket, RawSocketOption.levelSocket, 9), 1);
expect(_readIntOption(socket, RawSocketOption.levelTcp, 4), 30);
expect(_readIntOption(socket, RawSocketOption.levelTcp, 5), 10);
expect(_readIntOption(socket, RawSocketOption.levelTcp, 6), 3);
} finally {
await service.disconnect();
await server.close();
}
},
skip: Platform.isLinux ? false : 'Option numbers checked are Linux ones',
);
test('connect/disconnect updates TCP transport state', () async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final service = TcpTransportService();
+30 -1
View File
@@ -105,7 +105,7 @@ void main() {
final packets = decoder.ingest(
Uint8List.fromList(<int>[
usbSerialRxFrameStart,
0xAD,
usbSerialMaxRxPayloadLength + 1,
0x00,
0x99,
usbSerialRxFrameStart,
@@ -121,6 +121,35 @@ void main() {
},
);
test(
'UsbSerialFrameDecoder accepts firmware frames up to 176 bytes and keeps the next frame',
() {
final decoder = UsbSerialFrameDecoder();
final payload = Uint8List(usbSerialMaxRxPayloadLength);
for (var i = 0; i < payload.length; i++) {
// Include stray frame-start bytes inside the payload.
payload[i] = i.isEven ? usbSerialTxFrameStart : usbSerialRxFrameStart;
}
final packets = decoder.ingest(
Uint8List.fromList(<int>[
usbSerialRxFrameStart,
usbSerialMaxRxPayloadLength & 0xff,
usbSerialMaxRxPayloadLength >> 8,
...payload,
usbSerialRxFrameStart,
0x01,
0x00,
0x06,
]),
);
expect(packets, hasLength(2));
expect(packets[0].payload, orderedEquals(payload));
expect(packets[1].payload, orderedEquals(<int>[0x06]));
},
);
test('UsbSerialFrameDecoder reset clears buffered partial data', () {
final decoder = UsbSerialFrameDecoder();
@@ -0,0 +1,223 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/smaz.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/message.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _device = 'abcdef012345';
const _contact = 'c1';
Future<void> _init([Map<String, Object> values = const {}]) async {
SharedPreferences.setMockInitialValues(values);
PrefsManager.reset();
await PrefsManager.initialize();
MessageStore().forgetArchive();
ChannelMessageStore().forgetArchive();
}
Message _dm(int i, {String? text}) => Message(
senderKey: Uint8List.fromList([1, 2, 3]),
text: text ?? 'm$i',
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 * i),
isOutgoing: false,
status: MessageStatus.delivered,
messageId: 'id$i',
);
ChannelMessage _ch(int i) => ChannelMessage(
senderKey: null,
senderName: 'Bob',
text: 'c$i',
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 * i),
isOutgoing: false,
status: ChannelMessageStatus.sent,
channelIndex: 0,
messageId: 'cid$i',
);
MessageStore _messageStore() => MessageStore()..setPublicKeyHex = _device;
void main() {
group('MessageStore window persistence', () {
test('saving the window keeps archived history ahead of it', () async {
await _init();
final store = _messageStore();
final all = [for (var i = 0; i < 10; i++) _dm(i)];
await store.saveMessages(_contact, all);
final loaded = await store.loadMessages(_contact);
final window = loaded.sublist(6);
store.setArchived(_contact, loaded.sublist(0, 6));
await store.saveMessages(_contact, [...window, _dm(10)]);
final reloaded = await store.loadMessages(_contact);
expect(reloaded.map((m) => m.text), [
for (var i = 0; i <= 10; i++) 'm$i',
]);
});
test('trimmed messages are archived, deletes stay deleted', () async {
await _init();
final store = _messageStore();
store.setArchived(_contact, const []);
final window = [for (var i = 0; i < 4; i++) _dm(i)];
await store.saveMessages(_contact, window);
// Trim the oldest two out of the window, delete one still in it.
store.archive(_contact, window.sublist(0, 2));
final remaining = [window[3], _dm(4)];
await store.saveMessages(_contact, remaining);
final reloaded = await store.loadMessages(_contact);
expect(reloaded.map((m) => m.text), ['m0', 'm1', 'm3', 'm4']);
expect(store.archivedCount(_contact), 2);
store.unarchiveNewest(_contact, 1);
expect(store.archivedCount(_contact), 1);
});
test('an unreconciled save merges with what is stored', () async {
await _init();
final store = _messageStore();
await store.saveMessages(_contact, [for (var i = 0; i < 5; i++) _dm(i)]);
// A fresh session saves a new message before the history was loaded.
store.forgetArchive();
await store.saveMessages(_contact, [_dm(5)]);
final reloaded = await store.loadMessages(_contact);
expect(reloaded.map((m) => m.text), [for (var i = 0; i <= 5; i++) 'm$i']);
});
test('clearMessages wipes archived history too', () async {
await _init();
final store = _messageStore();
store.setArchived(_contact, [_dm(0), _dm(1)]);
await store.saveMessages(_contact, [_dm(2)]);
await store.clearMessages(_contact);
await store.saveMessages(_contact, [_dm(3)]);
final reloaded = await store.loadMessages(_contact);
expect(reloaded.map((m) => m.text), ['m3']);
});
test('storage is capped by dropping the oldest archived entries', () async {
await _init();
final store = _messageStore();
const cap = MessageStore.maxStoredMessages;
store.setArchived(_contact, [for (var i = 0; i < cap; i++) _dm(i)]);
await store.saveMessages(_contact, [_dm(cap), _dm(cap + 1)]);
final reloaded = await store.loadMessages(_contact);
expect(reloaded.length, cap);
expect(reloaded.first.text, 'm2');
expect(reloaded.last.text, 'm${cap + 1}');
expect(store.archivedCount(_contact), cap - 2);
});
});
group('MessageStore decoding', () {
test('plain text that looks like Smaz survives a reload', () async {
await _init();
final store = _messageStore();
await store.saveMessages(_contact, [
_dm(0, text: 's:test'),
_dm(1, text: 's:abcd'),
]);
final reloaded = await store.loadMessages(_contact);
expect(reloaded.map((m) => m.text), ['s:test', 's:abcd']);
});
test('legacy records still decode real Smaz payloads', () async {
const plain = 'hello there how are you doing';
final encoded = Smaz.encodeIfSmaller(plain);
expect(encoded, startsWith('s:'));
await _init({
'messages_${_device.substring(0, 10)}$_contact': jsonEncode([
{
'senderKey': base64Encode([1, 2, 3]),
'text': encoded,
'timestamp': 1000,
},
{
'senderKey': base64Encode([1, 2, 3]),
'text': 's:test',
'timestamp': 2000,
},
]),
});
final reloaded = await _messageStore().loadMessages(_contact);
expect(reloaded.map((m) => m.text), [plain, 's:test']);
});
test('a corrupt reaction status does not drop the message', () async {
await _init({
'messages_${_device.substring(0, 10)}$_contact': jsonEncode([
{
'senderKey': base64Encode([1, 2, 3]),
'text': 'hi',
'timestamp': 1000,
'reactionStatuses': {'👍': 99, '❤': 'x', '😀': 1},
},
]),
});
final reloaded = await _messageStore().loadMessages(_contact);
expect(reloaded.single.text, 'hi');
expect(reloaded.single.reactionStatuses, {'😀': MessageStatus.values[1]});
});
});
group('ChannelMessageStore window persistence', () {
test('saving the window keeps archived history ahead of it', () async {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _device;
final all = [for (var i = 0; i < 8; i++) _ch(i)];
await store.saveChannelMessages(0, all);
final loaded = await store.loadChannelMessages(0);
store.setArchived(0, loaded.sublist(0, 5));
await store.saveChannelMessages(0, [...loaded.sublist(5), _ch(8)]);
final reloaded = await store.loadChannelMessages(0);
expect(reloaded.map((m) => m.text), [for (var i = 0; i <= 8; i++) 'c$i']);
});
test('clearing through another instance resets the archive', () async {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _device;
store.setArchived(0, [_ch(0), _ch(1)]);
await store.saveChannelMessages(0, [_ch(2)]);
await (ChannelMessageStore()..setPublicKeyHex = _device)
.clearChannelMessages(0);
await store.saveChannelMessages(0, [_ch(3)]);
final reloaded = await store.loadChannelMessages(0);
expect(reloaded.map((m) => m.text), ['c3']);
});
});
group('Smaz.tryDecodePrefixed', () {
test('rejects plain text that is not a canonical compressed payload', () {
expect(Smaz.tryDecodePrefixed('s:test'), isNull);
expect(Smaz.tryDecodePrefixed('s:done'), isNull);
expect(Smaz.tryDecodePrefixed('s:hello'), isNull);
});
test('decodes what encodeIfSmaller produced', () {
for (final plain in [
'hello there how are you doing',
'ok see you at the meeting',
]) {
expect(Smaz.tryDecodePrefixed(Smaz.encodeIfSmaller(plain)), plain);
}
});
});
}
+184
View File
@@ -0,0 +1,184 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/cyr2lat.dart';
import 'package:meshcore_open/models/path_history.dart';
import 'package:meshcore_open/review_mode/review_mode_storage.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/storage/channel_region_store.dart';
import 'package:meshcore_open/storage/channel_store.dart';
import 'package:meshcore_open/storage/contact_discovery_store.dart';
import 'package:meshcore_open/storage/legacy_key_migration.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/storage/region_store.dart';
import 'package:meshcore_open/storage/unread_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _radioA = 'aaaaaaaaaa';
const _radioB = 'bbbbbbbbbb';
Future<void> _init(Map<String, Object> values) async {
SharedPreferences.setMockInitialValues(values);
PrefsManager.reset();
await PrefsManager.initialize();
}
void main() {
tearDown(() {
scopesWithoutLegacyMigration.clear();
TimeoutPredictionService.recordingSuspended = false;
});
test(
'channel store skips a malformed channel instead of dropping all',
() async {
await _init({
'channels$_radioA': jsonEncode([
{'index': 0, 'name': 'Public'},
{'index': 'bad', 'name': 'Broken'},
{'index': 2, 'name': 'Second'},
]),
});
final store = ChannelStore()..setPublicKeyHex = _radioA;
final channels = await store.loadChannels();
expect(channels.map((c) => c.name), ['Public', 'Second']);
},
);
test('unread store keeps valid counts when one is malformed', () async {
await _init({
'contact_unread_count$_radioA': jsonEncode({'a': 3, 'b': 'oops', 'c': 1}),
});
final store = UnreadStore()..setPublicKeyHex = _radioA;
expect(await store.loadContactUnreadCount(), {'a': 3, 'c': 1});
});
test(
'discovery store does not migrate legacy data into review scope',
() async {
await _init({'discovered_contacts': '[]'});
final reviewScope = ReviewRadio.storagePrefix;
scopesWithoutLegacyMigration.add(reviewScope);
final store = ContactDiscoveryStore()
..setPublicKeyHex = '${reviewScope}00';
expect(await store.loadContacts(), isEmpty);
expect(PrefsManager.instance.getString('discovered_contacts'), '[]');
expect(PrefsManager.instance.getKeys(), isNot(contains(store.keyFor)));
},
);
group('path history scoping', () {
final history = jsonEncode(
ContactPathHistory(contactPubKeyHex: 'c1', recentPaths: []).toJson(),
);
test('clearAllPathHistories only clears the connected radio', () async {
await _init({
'path_history_${_radioA}_c1': history,
'path_history_${_radioB}_c1': history,
'path_history_c2': history,
});
final storage = StorageService()..setPublicKeyHex = '${_radioA}xx';
await storage.clearAllPathHistories();
final keys = PrefsManager.instance.getKeys();
expect(keys, contains('path_history_${_radioB}_c1'));
expect(keys, isNot(contains('path_history_${_radioA}_c1')));
expect(keys, isNot(contains('path_history_c2')));
});
test('legacy history migrates once into the first radio', () async {
await _init({'path_history_c1': history});
final a = StorageService()..setPublicKeyHex = '${_radioA}xx';
expect(await a.loadPathHistory('c1'), isNotNull);
final keys = PrefsManager.instance.getKeys();
expect(keys, contains('path_history_${_radioA}_c1'));
expect(keys, isNot(contains('path_history_c1')));
final b = StorageService()..setPublicKeyHex = '${_radioB}xx';
expect(await b.loadPathHistory('c1'), isNull);
});
test('review scope does not adopt legacy history', () async {
await _init({'path_history_c1': history});
scopesWithoutLegacyMigration.add(_radioA);
final a = StorageService()..setPublicKeyHex = '${_radioA}xx';
expect(await a.loadPathHistory('c1'), isNull);
expect(PrefsManager.instance.getKeys(), contains('path_history_c1'));
});
});
test('removing a region clears assignments on every radio', () async {
await _init({
'regions': ['EU', 'US'],
'channel_region_${_radioA}1': 'EU',
'channel_region_${_radioB}3': 'EU',
'channel_region_${_radioB}4': 'US',
'default_region_$_radioB': 'EU',
});
final store = RegionStore()..setPublicKeyHex = '${_radioA}xx';
await store.removeRegion('EU');
final prefs = PrefsManager.instance;
expect(prefs.getStringList('regions'), ['US']);
expect(prefs.getString('channel_region_${_radioA}1'), '');
expect(prefs.getString('channel_region_${_radioB}3'), '');
expect(prefs.getString('channel_region_${_radioB}4'), 'US');
expect(prefs.getString('default_region_$_radioB'), '');
final regionB = ChannelRegionStore()..setPublicKeyHex = '${_radioB}xx';
expect(regionB.loadDefaultRegion(), '');
});
group('review mode session', () {
test('restores repeater keys and suspends delivery recording', () async {
await _init({
'repeater_passwords': jsonEncode({'real': 'secret'}),
});
await beginReviewModeSession(null);
expect(TimeoutPredictionService.recordingSuspended, isTrue);
final storage = StorageService();
await storage.saveRepeaterPassword('fake', 'pw');
await storage.setRepeaterAutoClockSyncAfterLoginEnabled('fake', true);
final predictor = TimeoutPredictionService.noStorage();
predictor.recordObservation(
contactKey: 'fake',
pathLength: 1,
messageBytes: 10,
tripTimeMs: 1500,
);
expect(predictor.observationCount, 0);
await endReviewModeSession(null);
expect(TimeoutPredictionService.recordingSuspended, isFalse);
expect(await storage.loadRepeaterPasswords(), {'real': 'secret'});
expect(
PrefsManager.instance.containsKey(
'repeater_auto_clock_sync_after_login',
),
isFalse,
);
});
test('interrupted session snapshot survives a second begin', () async {
await _init({
'repeater_passwords': jsonEncode({'real': 'secret'}),
});
await beginReviewModeSession(null);
await StorageService().saveRepeaterPassword('fake', 'pw');
// App killed, review started again before startup cleanup ran.
await beginReviewModeSession(null);
await endReviewModeSession(null);
expect(await StorageService().loadRepeaterPasswords(), {
'real': 'secret',
});
});
});
group('Cyr2Lat sender prefix', () {
test('only the leading mention is kept untransliterated', () {
// Uses the default char map (р→p, о→o, с→c).
expect(Cyr2Lat.encode('@[Bob] рос [x] рос'), '@[Bob] poc [x] poc');
expect(Cyr2Lat.extractSenderName('@[Bob] рос [x] рос'), '@[Bob] ');
});
});
}
@@ -0,0 +1,55 @@
import 'package:flutter/material.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/widgets/translated_message_content.dart';
double _renderedScaleFactor(WidgetTester tester) {
final linkify = find.byType(Linkify);
if (linkify.evaluate().isNotEmpty) {
return tester.widget<Linkify>(linkify.first).textScaleFactor;
}
return tester
.widget<SelectableLinkify>(find.byType(SelectableLinkify).first)
.textScaleFactor;
}
Future<void> _pump(WidgetTester tester, TextScaler scaler) {
return tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: MediaQueryData(textScaler: scaler),
child: const Scaffold(
body: TranslatedMessageContent(
displayText: 'hello https://example.com',
originalText: 'bonjour',
style: TextStyle(fontSize: 16),
),
),
),
),
);
}
void main() {
testWidgets('message body follows the system text scale', (tester) async {
await _pump(tester, TextScaler.noScaling);
expect(_renderedScaleFactor(tester), 1.0);
await _pump(tester, const TextScaler.linear(2));
expect(_renderedScaleFactor(tester), 2.0);
});
testWidgets('original and translated text both scale', (tester) async {
await _pump(tester, const TextScaler.linear(1.5));
final factors = [
...tester
.widgetList<Linkify>(find.byType(Linkify))
.map((w) => w.textScaleFactor),
...tester
.widgetList<SelectableLinkify>(find.byType(SelectableLinkify))
.map((w) => w.textScaleFactor),
];
expect(factors, hasLength(2));
expect(factors, everyElement(1.5));
});
}