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,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();