Merge upstream/dev (9 commits) [upstream-sync]

Konflikt v lib/screens/channel_chat_screen.dart: upstream přidal do
_buildMessageBubble parametr showFilterBanner (filtr spamu), my tam máme
terminálový styl. V terminálovém režimu se banner (není spam / skrýt)
vykreslí nad řádkem zprávy, jinak by filtrované zprávy přišly o akce.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-11-08 00:43:30 +01:00
commit 8a9d9ba0b7
86 files changed
+13643 -301

No files matched your search

@@ -0,0 +1,434 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:crypto/crypto.dart' as crypto;
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/channel.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/review_mode/review_frames.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/review_mode/review_script.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/path_history_service.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:pointycastle/export.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: 20));
}
}
Uint8List _psk(int slot) =>
Channel.parsePskHex(ReviewScript.channels[slot].pskHex);
class _TestRadio extends ReviewRadio {
_TestRadio()
: super(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(milliseconds: 50),
replyDelay: const Duration(hours: 1),
);
}
Uint8List _logRxGroupText(Uint8List psk, String text, int timestampSecs) {
final plain = BytesBuilder()
..add(
Uint8List(4)
..buffer.asByteData().setUint32(0, timestampSecs, Endian.little),
)
..addByte(0)
..add(utf8.encode(text))
..addByte(0);
final padded = Uint8List(((plain.length + 15) ~/ 16) * 16)
..setRange(0, plain.length, plain.toBytes());
final cipher = ECBBlockCipher(AESEngine())..init(true, KeyParameter(psk));
final encrypted = Uint8List(padded.length);
for (var i = 0; i < padded.length; i += 16) {
cipher.processBlock(padded, i, encrypted, i);
}
final key32 = Uint8List(32)..setRange(0, 16, psk);
final mac = crypto.Hmac(crypto.sha256, key32).convert(encrypted).bytes;
final channelHash = crypto.sha256.convert(psk).bytes[0];
return Uint8List.fromList([
pushCodeLogRxData,
40, // snr
0xA0, // rssi
0x15, // flood route, GRP_TXT payload
0x00, // no path
channelHash,
mac[0],
mac[1],
...encrypted,
]);
}
late MeshCoreConnector _connector;
late MessageFilterService _filter;
Future<void> _connect() async {
final radio = _TestRadio();
_connector.reviewRadioFactoryForTest = () => radio;
await _connector.connectReview();
addTearDown(_connector.disconnect);
await _waitFor(() => _connector.channelMapConfirmed);
}
Channel _channelAt(int slot) =>
_connector.channels.firstWhere((c) => c.index == slot);
ChannelMessage? _find(int slot, String text) {
for (final m in _connector.getChannelMessages(_channelAt(slot))) {
if (m.text == text) return m;
}
return null;
}
int _nowSecs() => DateTime.now().millisecondsSinceEpoch ~/ 1000;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
_filter = MessageFilterService();
await _filter.load();
await _filter.addRule(
FilterRule(id: MessageFilterService.newRuleId(), pattern: 'meshos'),
);
_connector = MeshCoreConnector();
final retryService = MessageRetryService();
_connector.initialize(
retryService: retryService,
pathHistoryService: PathHistoryService(StorageService()),
messageFilterService: _filter,
);
addTearDown(() {
_connector.dispose();
retryService.dispose();
_filter.dispose();
});
});
test('applyFilterVerdict tags the message, or leaves it alone', () {
final message = ChannelMessage(
senderKey: null,
senderName: 'Sam',
text: 'hello',
timestamp: DateTime(2026),
isOutgoing: false,
status: ChannelMessageStatus.sent,
);
expect(
identical(MeshCoreConnector.applyFilterVerdict(message, null), message),
isTrue,
);
final tagged = MeshCoreConnector.applyFilterVerdict(
message,
const FilterVerdict(reason: FilterReason.textRule, detail: 'meshos'),
);
expect(tagged.isFiltered, isTrue);
expect(tagged.filterReason, 'textRule');
expect(tagged.filterDetail, 'meshos');
});
test('a channel message matching a rule is stored tagged and does not '
'count as unread', () async {
await _connect();
final channel = _channelAt(2);
final unreadBefore = channel.unreadCount;
_connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: 2,
sender: 'Spammer',
message: 'Try MeshOS today, free download',
timestampSecs: _nowSecs(),
),
);
_connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: 2,
sender: 'Sam',
message: 'Anyone up for a hike on Sunday?',
timestampSecs: _nowSecs() + 1,
),
);
await _waitFor(() => _find(2, 'Anyone up for a hike on Sunday?') != null);
final spam = _find(2, 'Try MeshOS today, free download')!;
expect(spam.filterReason, filterReasonToJson(FilterReason.textRule));
expect(spam.filterDetail, 'meshos');
final clean = _find(2, 'Anyone up for a hike on Sunday?')!;
expect(clean.isFiltered, isFalse);
// Only the clean message counts as unread.
expect(channel.unreadCount, unreadBefore + 1);
expect(_connector.latestVisibleChannelMessage(channel)?.text, clean.text);
final filtered = _connector.recentFilteredChannelMessages();
expect(filtered.map((e) => e.$2.messageId), contains(spam.messageId));
expect(
filtered.firstWhere((e) => e.$2.messageId == spam.messageId).$1.index,
2,
);
});
test('an RX-log message matching a rule is stored tagged', () async {
await _connect();
final channel = _channelAt(2);
final unreadBefore = channel.unreadCount;
_connector.handleFrameForTest(
_logRxGroupText(_psk(2), 'Bot: get meshos now', _nowSecs()),
);
await _waitFor(() => _find(2, 'get meshos now') != null);
final message = _find(2, 'get meshos now')!;
expect(message.filterReason, filterReasonToJson(FilterReason.textRule));
expect(channel.unreadCount, unreadBefore);
expect(
_connector.latestVisibleChannelMessage(channel)?.text,
isNot('get meshos now'),
);
});
test('mark spam and not spam update the stored message', () async {
await _connect();
const text = 'Selling radios cheap, message me';
_connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: 2,
sender: 'Trader',
message: text,
timestampSecs: _nowSecs(),
),
);
await _waitFor(() => _find(2, text) != null);
final message = _find(2, text)!;
expect(message.isFiltered, isFalse);
final spamBefore = _filter.spamExampleCount;
await _connector.markChannelMessageSpam(_channelAt(2), message);
expect(_find(2, text)!.filterReason, 'manual');
expect(_find(2, text)!.filterDetail, isNull);
expect(_filter.spamExampleCount, spamBefore + 1);
final notSpamBefore = _filter.notSpamExampleCount;
await _connector.markChannelMessageNotSpam(_channelAt(2), _find(2, text)!);
expect(_find(2, text)!.isFiltered, isFalse);
expect(_filter.notSpamExampleCount, notSpamBefore + 1);
});
test('spam on a reply whose target is not loaded replaces its clean '
'example', () async {
await _connect();
// Nobody called "Ghost" has posted, so the reply keeps its mention.
const text = '@[Ghost] cheap radios for sale, message me today';
final cleanBefore = _filter.recentCleanCount;
_connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: 2,
sender: 'Seller',
message: text,
timestampSecs: _nowSecs(),
),
);
await _waitFor(() => _find(2, text) != null);
final message = _find(2, text)!;
expect(message.text, startsWith('@[Ghost]'));
expect(_filter.recentCleanCount, cleanBefore + 1);
final spamBefore = _filter.spamExampleCount;
await _connector.markChannelMessageSpam(_channelAt(2), message);
expect(_filter.spamExampleCount, spamBefore + 1);
// The clean example recorded on arrival is gone, not contradicted.
expect(_filter.recentCleanCount, cleanBefore);
});
test('spam actions only touch the message in the chosen channel', () async {
await _connect();
// Any two configured channels.
final channels = _connector.channels.where((c) => !c.isEmpty).toList();
expect(channels.length, greaterThanOrEqualTo(2));
final first = channels[0];
final second = channels[1];
const text = 'Same words posted to two channels at once';
final ts = _nowSecs();
for (final channel in [first, second]) {
_connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Twin',
message: text,
timestampSecs: ts,
),
);
}
await _waitFor(
() =>
_find(first.index, text) != null && _find(second.index, text) != null,
);
final inFirst = _find(first.index, text)!;
final inSecond = _find(second.index, text)!;
// Message ids do not include the channel, so these collide.
expect(inSecond.messageId, inFirst.messageId);
await _connector.markChannelMessageSpam(second, inSecond);
expect(_find(second.index, text)!.filterReason, 'manual');
expect(_find(first.index, text)!.isFiltered, isFalse);
// Not spam on the first channel must not un-hide the second.
await _connector.markChannelMessageSpam(first, _find(first.index, text)!);
await _connector.markChannelMessageNotSpam(
first,
_find(first.index, text)!,
);
expect(_find(first.index, text)!.isFiltered, isFalse);
expect(_find(second.index, text)!.filterReason, 'manual');
});
test('channels excluded from filtering keep every message visible', () async {
await _connect();
final channel = _channelAt(2);
await _filter.setChannelExcluded(
MeshCoreConnector.messageFilterChannelId(channel),
true,
);
addTearDown(
() => _filter.setChannelExcluded(
MeshCoreConnector.messageFilterChannelId(channel),
false,
),
);
_connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: 2,
sender: 'Spammer',
message: 'meshos in an excluded channel',
timestampSecs: _nowSecs(),
),
);
await _waitFor(() => _find(2, 'meshos in an excluded channel') != null);
expect(_find(2, 'meshos in an excluded channel')!.isFiltered, isFalse);
});
test(
'an exact rule matches a reply by its text without the mention',
() async {
await _connect();
const text = 'exact spam phrase here';
await _filter.addRule(
const FilterRule(
id: 'exact-reply',
pattern: text,
match: FilterRuleMatch.exact,
),
);
addTearDown(() => _filter.removeRule('exact-reply'));
_connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: 2,
sender: 'Replier',
message: '@[Sam] $text',
timestampSecs: _nowSecs(),
),
);
// The stored text drops the mention only when the reply target is
// known; either way the rule sees the text without it.
ChannelMessage? reply() => _find(2, text) ?? _find(2, '@[Sam] $text');
await _waitFor(() => reply() != null);
expect(reply()!.filterReason, 'textRule');
},
);
test('previews include filtered messages when the channel is not '
'filtered', () async {
await _connect();
final channel = _channelAt(2);
const text = 'meshos preview check';
_connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: 2,
sender: 'Spammer',
message: text,
timestampSecs: _nowSecs() + 5,
),
);
await _waitFor(() => _find(2, text) != null);
expect(_find(2, text)!.isFiltered, isTrue);
expect(_connector.latestVisibleChannelMessage(channel)?.text, isNot(text));
final channelId = MeshCoreConnector.messageFilterChannelId(channel);
await _filter.setChannelExcluded(channelId, true);
addTearDown(() => _filter.setChannelExcluded(channelId, false));
expect(_connector.latestVisibleChannelMessage(channel)?.text, text);
});
test('rule changes apply to messages already in the chat', () async {
await _connect();
const text = 'Cheap antennas at the swap meet, ask me';
_connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: 2,
sender: 'Vendor',
message: text,
timestampSecs: _nowSecs(),
),
);
await _waitFor(() => _find(2, text) != null);
expect(_find(2, text)!.isFiltered, isFalse);
// A new rule hides the message that already arrived...
await _filter.addRule(const FilterRule(id: 'retro', pattern: 'antennas'));
expect(
_find(2, text)!.filterReason,
filterReasonToJson(FilterReason.textRule),
);
expect(_find(2, text)!.filterDetail, 'antennas');
// ...and deleting it shows the message again.
await _filter.removeRule('retro');
expect(_find(2, text)!.isFiltered, isFalse);
// Other filter reasons are not touched by rule changes.
await _connector.markChannelMessageSpam(_channelAt(2), _find(2, text)!);
await _filter.addRule(const FilterRule(id: 'retro2', pattern: 'swap'));
await _filter.removeRule('retro2');
expect(_find(2, text)!.filterReason, 'manual');
});
test('mesh copies of one message are stored and filtered once', () async {
await _connect();
const text = 'Weather net starts at seven tonight on the hill';
final ts = _nowSecs();
final cleanBefore = _filter.recentCleanCount;
_connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: 2,
sender: 'Relay',
message: text,
timestampSecs: ts,
),
);
_connector.handleFrameForTest(_logRxGroupText(_psk(2), 'Relay: $text', ts));
_connector.handleFrameForTest(_logRxGroupText(_psk(2), 'Relay: $text', ts));
await _waitFor(() => _find(2, text) != null);
await Future<void>.delayed(const Duration(milliseconds: 100));
final copies = _connector
.getChannelMessages(_channelAt(2))
.where((m) => m.text == text)
.toList();
expect(copies, hasLength(1));
// Not mistaken for the sender repeating themselves.
expect(copies.single.isFiltered, isFalse);
expect(_filter.recentCleanCount, cleanBefore + 1);
});
}
@@ -0,0 +1,57 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
ChannelMessage _msg({String? reason, String? detail}) => ChannelMessage(
senderName: 'Alice',
text: 'hello',
timestamp: DateTime.fromMillisecondsSinceEpoch(1000),
isOutgoing: false,
messageId: 'm1',
filterReason: reason,
filterDetail: detail,
);
void main() {
test('isFiltered reflects filterReason', () {
expect(_msg().isFiltered, isFalse);
expect(_msg(reason: 'manual').isFiltered, isTrue);
});
test('copyWith sets, keeps and clears filter fields', () {
final filtered = _msg().copyWith(
filterReason: 'textRule',
filterDetail: 'spam',
);
expect(filtered.filterReason, 'textRule');
expect(filtered.filterDetail, 'spam');
final kept = filtered.copyWith(repeatCount: 2);
expect(kept.filterReason, 'textRule');
expect(kept.filterDetail, 'spam');
final cleared = filtered.copyWith(clearFilter: true);
expect(cleared.isFiltered, isFalse);
expect(cleared.filterDetail, isNull);
});
test('store round-trips filter fields and omits them when null', () async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
final store = ChannelMessageStore()..setPublicKeyHex = 'abcdef012345';
store.forgetArchive();
await store.saveChannelMessages('c1', [
_msg(reason: 'textRule', detail: 'spam'),
]);
var loaded = await store.loadChannelMessages('c1');
expect(loaded.single.filterReason, 'textRule');
expect(loaded.single.filterDetail, 'spam');
store.forgetArchive();
await store.saveChannelMessages('c2', [_msg()]);
loaded = await store.loadChannelMessages('c2');
expect(loaded.single.filterReason, isNull);
expect(loaded.single.filterDetail, isNull);
});
}
@@ -0,0 +1,280 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/screens/channel_chat_transcript_grouping.dart';
final _day1 = DateTime(2026, 3, 1, 12);
final _day2 = DateTime(2026, 3, 2, 12);
TranscriptRowInfo _msg(String id, {bool filtered = false, DateTime? at}) =>
TranscriptRowInfo(id: id, receivedAt: at ?? _day1, isFiltered: filtered);
TranscriptRowInfo _img(String id, {bool filtered = false}) => TranscriptRowInfo(
id: id,
receivedAt: _day1,
isImage: true,
isFiltered: filtered,
);
bool _sameDay(DateTime a, DateTime b) =>
a.year == b.year && a.month == b.month && a.day == b.day;
/// Compact description: plain rows by id, ghosts as `[ids]`, the header above
/// a revealed run as `^[ids]`.
List<String> _describe(
List<TranscriptRowInfo> rows,
List<TranscriptEntry> entries,
) => [
for (final e in entries)
e.isGhost
? '${e.expanded ? '^' : ''}[${e.rows.map((r) => rows[r].id).join(',')}]'
: rows[e.row].id,
];
void main() {
group('groupFilteredRows', () {
test('no filtered rows leaves every row as its own entry', () {
final rows = [_msg('a'), _msg('b'), _msg('c')];
final entries = groupFilteredRows(
rows,
mode: FilterDisplayMode.placeholder,
);
expect(_describe(rows, entries), ['a', 'b', 'c']);
expect(entries.every((e) => !e.isGhost), isTrue);
});
test('placeholder mode collapses each run into one ghost', () {
final rows = [
_msg('a'),
_msg('s1', filtered: true),
_msg('s2', filtered: true),
_msg('s3', filtered: true),
_msg('b'),
_msg('s4', filtered: true),
];
final entries = groupFilteredRows(
rows,
mode: FilterDisplayMode.placeholder,
);
expect(_describe(rows, entries), ['a', '[s1,s2,s3]', 'b', '[s4]']);
// The ghost id follows its newest member (first in newest-first order).
expect(entries[1].id, 'ghost:s1');
expect(entries[3].id, 'ghost:s4');
expect(entries[0].id, 'a');
});
test('hide mode drops filtered rows entirely', () {
final rows = [
_msg('a'),
_msg('s1', filtered: true),
_msg('s2', filtered: true),
_msg('b'),
];
final entries = groupFilteredRows(rows, mode: FilterDisplayMode.hide);
expect(_describe(rows, entries), ['a', 'b']);
});
test(
'revealed ids render as normal rows under a header and split runs',
() {
final rows = [
_msg('s1', filtered: true),
_msg('s2', filtered: true),
_msg('s3', filtered: true),
];
final entries = groupFilteredRows(
rows,
mode: FilterDisplayMode.placeholder,
revealedIds: {'s2'},
);
expect(_describe(rows, entries), ['[s1]', '^[s2]', '[s3]']);
final hidden = groupFilteredRows(
rows,
mode: FilterDisplayMode.hide,
revealedIds: {'s2'},
);
expect(_describe(rows, hidden), ['s2']);
},
);
test('a fully revealed run stays one entry with a stable id', () {
final rows = [
_msg('a'),
_msg('s1', filtered: true),
_msg('s2', filtered: true),
_msg('s3', filtered: true),
_msg('b'),
];
final collapsed = groupFilteredRows(
rows,
mode: FilterDisplayMode.placeholder,
);
final expanded = groupFilteredRows(
rows,
mode: FilterDisplayMode.placeholder,
revealedIds: {'s1', 's2', 's3'},
);
expect(_describe(rows, expanded), ['a', '^[s1,s2,s3]', 'b']);
// Same id in both states, so the UI can animate it in place.
expect(expanded[1].id, collapsed[1].id);
expect(expanded[1].id, 'ghost:s1');
expect(collapsed[1].expanded, isFalse);
expect(expanded[1].expanded, isTrue);
// Scroll targets inside the run land on the run entry.
final byRow = entryIndexByRow(expanded, rows.length);
expect([for (var r = 0; r < rows.length; r++) byRow[r]], [0, 1, 1, 1, 2]);
});
test('images are never grouped and break a run', () {
final rows = [
_msg('s1', filtered: true),
_img('aeic:1', filtered: true),
_msg('s2', filtered: true),
];
final entries = groupFilteredRows(
rows,
mode: FilterDisplayMode.placeholder,
);
expect(_describe(rows, entries), ['[s1]', 'aeic:1', '[s2]']);
expect(
_describe(rows, groupFilteredRows(rows, mode: FilterDisplayMode.hide)),
['aeic:1'],
);
});
test('inactive filter shows filtered messages as normal rows', () {
final rows = [_msg('s1', filtered: true), _msg('a')];
final entries = groupFilteredRows(
rows,
mode: FilterDisplayMode.hide,
filterActive: false,
);
expect(_describe(rows, entries), ['s1', 'a']);
});
test('a run is split at a day boundary when sameDay is given', () {
final rows = [
_msg('s1', filtered: true, at: _day2),
_msg('s2', filtered: true, at: _day1),
_msg('s3', filtered: true, at: _day1),
];
expect(
_describe(
rows,
groupFilteredRows(
rows,
mode: FilterDisplayMode.placeholder,
sameDay: _sameDay,
),
),
['[s1]', '[s2,s3]'],
);
expect(
_describe(
rows,
groupFilteredRows(rows, mode: FilterDisplayMode.placeholder),
),
['[s1,s2,s3]'],
);
});
test('empty input yields no entries', () {
expect(
groupFilteredRows(const [], mode: FilterDisplayMode.placeholder),
isEmpty,
);
});
});
group('entryIndexByRow', () {
test('an unread anchor inside a ghost run maps to the ghost', () {
final rows = [
_msg('new'),
_msg('s1', filtered: true),
_msg('anchor', filtered: true),
_msg('old'),
];
final entries = groupFilteredRows(
rows,
mode: FilterDisplayMode.placeholder,
);
final byRow = entryIndexByRow(entries, rows.length);
expect(byRow[2], 1);
expect(entries[byRow[2]!].id, 'ghost:s1');
expect(byRow[0], 0);
expect(byRow[3], 2);
});
test('a row dropped in hide mode maps to the nearest newer entry', () {
final rows = [
_msg('new'),
_msg('s1', filtered: true),
_msg('s2', filtered: true),
_msg('old'),
];
final entries = groupFilteredRows(rows, mode: FilterDisplayMode.hide);
final byRow = entryIndexByRow(entries, rows.length);
expect(entries[byRow[1]!].id, 'new');
expect(entries[byRow[2]!].id, 'new');
expect(entries[byRow[3]!].id, 'old');
});
test('with nothing newer visible, hidden rows map to the older entry', () {
final rows = [
_msg('s1', filtered: true),
_msg('s2', filtered: true),
_msg('old'),
];
final entries = groupFilteredRows(rows, mode: FilterDisplayMode.hide);
final byRow = entryIndexByRow(entries, rows.length);
expect(entries[byRow[0]!].id, 'old');
expect(entries[byRow[1]!].id, 'old');
});
test('maps nothing when every row is hidden', () {
final rows = [_msg('s1', filtered: true)];
final entries = groupFilteredRows(rows, mode: FilterDisplayMode.hide);
expect(entryIndexByRow(entries, rows.length), isEmpty);
});
});
group('isReplyPreviewConcealed', () {
test('hides a quoted filtered message until it is revealed', () {
expect(
isReplyPreviewConcealed(
quotedIsFiltered: true,
filterActive: true,
quotedRevealed: false,
),
isTrue,
);
expect(
isReplyPreviewConcealed(
quotedIsFiltered: true,
filterActive: true,
quotedRevealed: true,
),
isFalse,
);
});
test('normal quotes, or filtering off for the channel, show as usual', () {
expect(
isReplyPreviewConcealed(
quotedIsFiltered: false,
filterActive: true,
quotedRevealed: false,
),
isFalse,
);
expect(
isReplyPreviewConcealed(
quotedIsFiltered: true,
filterActive: false,
quotedRevealed: false,
),
isFalse,
);
});
});
}
@@ -0,0 +1,77 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.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/screens/filtered_messages_screen.dart';
ChannelMessage _msg() => ChannelMessage(
senderName: 'Twin',
text: 'Same words posted to two channels at once',
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000),
isOutgoing: false,
);
void main() {
test('rows for colliding message ids in two channels stay distinct', () {
final first = Channel(
index: 1,
name: 'One',
psk: Uint8List.fromList(List.filled(16, 1)),
);
final second = Channel(
index: 2,
name: 'Two',
psk: Uint8List.fromList(List.filled(16, 2)),
);
final a = _msg();
final b = _msg();
// Message ids do not include the channel, so these collide...
expect(a.messageId, b.messageId);
// ...but the list rows (keys and reveal state) must not.
expect(
filteredMessageRowId(first, a),
isNot(filteredMessageRowId(second, b)),
);
expect(filteredMessageRowId(first, a), filteredMessageRowId(first, b));
});
testWidgets('collapsed cards shorten a whole-message rule pattern', (
tester,
) async {
const pattern =
'meshcore.co.uk is not a genuine site, the real one is meshcore.io';
final message = ChannelMessage(
senderName: 'SAY NO TO FRAUDS!',
text: pattern,
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000),
isOutgoing: false,
filterReason: 'textRule',
filterDetail: pattern,
);
late String collapsed;
late String revealed;
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Builder(
builder: (context) {
collapsed = messageFilterReasonText(context, message);
revealed = messageFilterReasonText(
context,
message,
revealed: true,
);
return const SizedBox();
},
),
),
);
expect(collapsed, isNot(contains(pattern)));
expect(collapsed, contains('…'));
expect(revealed, contains(pattern));
});
}
@@ -0,0 +1,242 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/screens/filtered_messages_screen.dart';
import 'package:meshcore_open/screens/message_filter_settings_screen.dart';
import 'package:meshcore_open/services/message_filter/message_filter_service.dart';
import 'package:meshcore_open/storage/message_filter_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/widgets/filter_rule_dialog.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
late MessageFilterService service;
late MeshCoreConnector connector;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
service = MessageFilterService(
store: MessageFilterStore(),
trainer: MessageFilterService.trainInline,
);
await service.load();
connector = MeshCoreConnector();
});
tearDown(() {
service.dispose();
connector.dispose();
});
Future<void> pumpScreen(WidgetTester tester) async {
// Tall enough that every section is laid out without scrolling.
tester.view.physicalSize = const Size(1080, 4000);
tester.view.devicePixelRatio = 2.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider<MeshCoreConnector>.value(value: connector),
ChangeNotifierProvider<MessageFilterService>.value(value: service),
],
child: const MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: MessageFilterSettingsScreen(),
),
),
);
await tester.pumpAndSettle();
}
testWidgets('renders every section with defaults', (tester) async {
await pumpScreen(tester);
expect(find.text('Message filter'), findsOneWidget);
expect(find.text('Filter messages'), findsOneWidget);
expect(find.text('Show a small placeholder'), findsOneWidget);
expect(find.text('Hide completely'), findsOneWidget);
expect(
find.text('Hidden messages stay in the Filtered messages list.'),
findsOneWidget,
);
expect(find.text('Filtered messages (0)'), findsOneWidget);
expect(
find.text(
'No rules yet. Add a word, phrase or sender name to hide messages '
'that match it.',
),
findsOneWidget,
);
expect(find.text('Repeated messages'), findsOneWidget);
expect(find.text('Repeated characters'), findsOneWidget);
expect(find.text('Learn from Spam taps'), findsOneWidget);
expect(find.text('0 spam and 0 not-spam examples'), findsOneWidget);
});
testWidgets('switches and display choice update the service', (tester) async {
await pumpScreen(tester);
await tester.tap(find.byKey(const ValueKey('messageFilter_enabledSwitch')));
await tester.pumpAndSettle();
expect(service.settings.enabled, isFalse);
await tester.tap(find.byKey(const ValueKey('messageFilter_displayHide')));
await tester.pumpAndSettle();
expect(service.settings.displayMode, FilterDisplayMode.hide);
await tester.tap(
find.byKey(const ValueKey('messageFilter_duplicatesSwitch')),
);
await tester.tap(
find.byKey(const ValueKey('messageFilter_repeatedCharactersSwitch')),
);
await tester.tap(
find.byKey(const ValueKey('messageFilter_learningSwitch')),
);
await tester.pumpAndSettle();
expect(service.settings.duplicates, isFalse);
expect(service.settings.repeatedCharacters, isFalse);
expect(service.settings.learning, isFalse);
});
testWidgets('add, edit and delete a rule with undo', (tester) async {
await pumpScreen(tester);
await tester.tap(find.byKey(const ValueKey('messageFilter_addRuleButton')));
await tester.pumpAndSettle();
expect(find.text('Add rule'), findsWidgets);
// Save stays disabled until something is typed.
final saveButton = find.widgetWithText(FilledButton, 'Save');
expect(tester.widget<FilledButton>(saveButton).onPressed, isNull);
await tester.enterText(find.byType(TextField), ' meshos ');
await tester.tap(find.byKey(const ValueKey('filterRuleField_both')));
await tester.tap(find.byKey(const ValueKey('filterRuleMatch_wholeWord')));
await tester.pumpAndSettle();
await tester.tap(saveButton);
await tester.pumpAndSettle();
expect(service.rules, hasLength(1));
final rule = service.rules.single;
expect(rule.pattern, 'meshos');
expect(rule.field, FilterRuleField.both);
expect(rule.match, FilterRuleMatch.wholeWord);
expect(rule.enabled, isTrue);
expect(find.text('meshos'), findsOneWidget);
expect(find.text('Both · Whole word'), findsOneWidget);
expect(find.text('Rule saved'), findsOneWidget);
// Turn it off from the list.
await tester.tap(
find.descendant(
of: find.byKey(ValueKey('messageFilter_rule_${rule.id}')),
matching: find.byType(Switch),
),
);
await tester.pumpAndSettle();
expect(service.rules.single.enabled, isFalse);
// Tap the row to edit; the id and enabled state are kept.
await tester.tap(find.text('meshos'));
await tester.pumpAndSettle();
expect(find.text('Edit rule'), findsOneWidget);
await tester.enterText(find.byType(TextField), 'meshos promo');
await tester.tap(find.widgetWithText(FilledButton, 'Save'));
await tester.pumpAndSettle();
expect(service.rules.single.id, rule.id);
expect(service.rules.single.pattern, 'meshos promo');
expect(service.rules.single.enabled, isFalse);
// Delete, then undo.
await tester.tap(find.byTooltip('Delete'));
await tester.pumpAndSettle();
expect(service.rules, isEmpty);
expect(find.text('Rule deleted'), findsOneWidget);
await tester.tap(find.text('Undo'));
await tester.pumpAndSettle();
expect(service.rules.single.pattern, 'meshos promo');
});
testWidgets('cancelling the dialog adds nothing', (tester) async {
await pumpScreen(tester);
await tester.tap(find.byKey(const ValueKey('messageFilter_addRuleButton')));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'spam');
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(service.rules, isEmpty);
});
testWidgets('reset learning asks first and clears examples', (tester) async {
await service.markSpam(sender: 'Bot', text: 'Buy cheap radios now');
await service.markNotSpam(
channelId: 'c',
sender: 'Ann',
text: 'See you at the meetup',
);
await pumpScreen(tester);
expect(find.text('1 spam and 1 not-spam examples'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('messageFilter_resetLearning')));
await tester.pumpAndSettle();
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(service.spamExampleCount, 1);
await tester.tap(find.byKey(const ValueKey('messageFilter_resetLearning')));
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(FilledButton, 'Reset learning'));
await tester.pumpAndSettle();
expect(service.spamExampleCount, 0);
expect(service.notSpamExampleCount, 0);
expect(find.text('0 spam and 0 not-spam examples'), findsOneWidget);
});
testWidgets('filtered messages tile opens the empty list', (tester) async {
await pumpScreen(tester);
await tester.tap(find.text('Filtered messages (0)'));
await tester.pumpAndSettle();
expect(find.byType(FilteredMessagesScreen), findsOneWidget);
expect(find.text('Nothing has been filtered.'), findsOneWidget);
});
testWidgets('dialog prefills a new rule from a message', (tester) async {
FilterRule? result;
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () async {
result = await showFilterRuleDialog(
context,
initialPattern: ' Bot ',
initialField: FilterRuleField.sender,
);
},
child: const Text('open'),
),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.text('Bot'), findsOneWidget);
await tester.tap(find.widgetWithText(FilledButton, 'Save'));
await tester.pumpAndSettle();
expect(result?.pattern, 'Bot');
expect(result?.field, FilterRuleField.sender);
expect(result?.match, FilterRuleMatch.contains);
expect(result?.id, isNotEmpty);
});
}
@@ -0,0 +1,308 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/services/message_filter/duplicate_tracker.dart';
void main() {
final t0 = DateTime(2026, 1, 1, 12);
test('same sender repeat within 10 minutes is a duplicate', () {
final tracker = DuplicateTracker();
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Anyone on the hill repeater?',
at: t0,
),
isNull,
);
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'anyone on the hill repeater!',
at: t0.add(const Duration(minutes: 9)),
),
FilterReason.duplicate,
);
});
test('short replies repeated by the same sender are not duplicates', () {
final tracker = DuplicateTracker();
for (final text in ['ok', 'test', 'yes sir', 'ok']) {
tracker.check(channelId: 'c', sender: 'Alice', text: text, at: t0);
}
for (final text in ['@[Bob] ok', 'test', 'yes sir']) {
expect(
tracker.check(
channelId: 'c',
sender: 'Alice',
text: text,
at: t0.add(const Duration(minutes: 5)),
),
isNull,
reason: text,
);
}
});
test('same sender repeat after the window is not a duplicate', () {
final tracker = DuplicateTracker();
tracker.check(channelId: 'c', sender: 'Bob', text: 'Hello', at: t0);
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Hello',
at: t0.add(const Duration(minutes: 11)),
),
isNull,
);
});
test('channels are tracked separately', () {
final tracker = DuplicateTracker();
tracker.check(channelId: 'a', sender: 'Bob', text: 'Hello', at: t0);
expect(
tracker.check(channelId: 'b', sender: 'Bob', text: 'Hello', at: t0),
isNull,
);
});
test('short greetings from many senders are never cross-sender', () {
final tracker = DuplicateTracker();
// New Year's Eve: everyone sends the same few words at once.
const greetings = [
'Happy New Year!',
'happy new year',
'HAPPY NEW YEAR!!',
'Happy new year 🎉',
'Happy New Year everyone!',
];
for (var i = 0; i < 8; i++) {
expect(
tracker.check(
channelId: 'c',
sender: 'person$i',
text: greetings[i % greetings.length],
at: t0.add(Duration(minutes: i)),
),
isNull,
reason: 'greeting from person$i must stay visible',
);
}
// Five words is still a greeting, not a campaign.
for (var i = 0; i < 4; i++) {
expect(
tracker.check(
channelId: 'c',
sender: 'friend$i',
text: 'Merry Christmas to you all',
at: t0.add(Duration(minutes: 10 + i)),
),
isNull,
);
}
});
test('third distinct sender of the same long text is cross-sender', () {
final tracker = DuplicateTracker();
const text = 'Join the best mesh client now, it is free';
expect(
tracker.check(channelId: 'c', sender: 'A', text: text, at: t0),
isNull,
);
expect(
tracker.check(
channelId: 'c',
sender: 'B',
text: text,
at: t0.add(const Duration(minutes: 5)),
),
isNull,
);
expect(
tracker.check(
channelId: 'c',
sender: 'C',
text: text,
at: t0.add(const Duration(minutes: 20)),
),
FilterReason.crossSenderDuplicate,
);
});
test('short texts never count as cross-sender duplicates', () {
final tracker = DuplicateTracker();
for (final sender in ['A', 'B', 'C', 'D']) {
expect(
tracker.check(channelId: 'c', sender: sender, text: 'hi all', at: t0),
isNull,
);
}
});
test('cross-sender window is 30 minutes', () {
final tracker = DuplicateTracker();
const text = 'Join the best mesh now';
tracker.check(channelId: 'c', sender: 'A', text: text, at: t0);
tracker.check(
channelId: 'c',
sender: 'B',
text: text,
at: t0.add(const Duration(minutes: 1)),
);
expect(
tracker.check(
channelId: 'c',
sender: 'C',
text: text,
at: t0.add(const Duration(minutes: 31)),
),
isNull,
);
});
test('filtered texts are still recorded so floods keep being caught', () {
final tracker = DuplicateTracker();
const text = 'buy cheap radios now';
tracker.check(channelId: 'c', sender: 'Bob', text: text, at: t0);
for (var i = 1; i <= 5; i++) {
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: text,
at: t0.add(Duration(minutes: 8 * i)),
),
FilterReason.duplicate,
);
}
});
test('allow exempts the text in that channel', () {
final tracker = DuplicateTracker();
tracker.check(channelId: 'c', sender: 'Bob', text: 'Hello', at: t0);
tracker.allow('c', 'HELLO!');
expect(tracker.isAllowed('c', 'hello'), isTrue);
expect(tracker.isAllowed('other', 'hello'), isFalse);
expect(
tracker.check(channelId: 'c', sender: 'Bob', text: 'Hello', at: t0),
isNull,
);
tracker.clear();
expect(tracker.isAllowed('c', 'hello'), isFalse);
});
test('empty normalized text is ignored', () {
final tracker = DuplicateTracker();
tracker.check(channelId: 'c', sender: 'Bob', text: '👍', at: t0);
expect(
tracker.check(channelId: 'c', sender: 'Bob', text: '👍', at: t0),
isNull,
);
});
group('send-time windows', () {
test('history synced in a burst is not a duplicate', () {
final tracker = DuplicateTracker();
// Sent three hours apart, delivered seconds apart after reconnecting.
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Heading out now',
at: t0,
receivedAt: t0.add(const Duration(hours: 5)),
),
isNull,
);
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Heading out now',
at: t0.add(const Duration(hours: 3)),
receivedAt: t0.add(const Duration(hours: 5, seconds: 2)),
),
isNull,
);
});
test('out-of-order delivery is still caught', () {
final tracker = DuplicateTracker();
// The newer copy arrives first.
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Buy cheap nodes',
at: t0.add(const Duration(minutes: 5)),
receivedAt: t0.add(const Duration(minutes: 30)),
),
isNull,
);
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Buy cheap nodes',
at: t0,
receivedAt: t0.add(const Duration(minutes: 30, seconds: 1)),
),
FilterReason.duplicate,
);
const campaign = 'the meshcore trademark grab is theft, boycott him';
final now = t0.add(const Duration(hours: 1));
for (final (i, sender) in ['x', 'y'].indexed) {
expect(
tracker.check(
channelId: 'c',
sender: sender,
text: campaign,
at: t0.add(Duration(minutes: 20 - i * 10)),
receivedAt: now,
),
isNull,
);
}
expect(
tracker.check(
channelId: 'c',
sender: 'z',
text: campaign,
at: t0,
receivedAt: now,
),
FilterReason.crossSenderDuplicate,
);
});
test('a sender clock years ahead does not evict other entries', () {
final tracker = DuplicateTracker();
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Morning all, testing my node',
at: t0,
);
tracker.check(
channelId: 'c',
sender: 'Wonky',
text: 'Clock is way off',
at: t0.add(const Duration(days: 900)),
receivedAt: t0.add(const Duration(minutes: 1)),
);
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Morning all, testing my node',
at: t0.add(const Duration(minutes: 2)),
),
FilterReason.duplicate,
);
});
});
}
@@ -0,0 +1,363 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/services/message_filter/message_filter_service.dart';
import 'package:meshcore_open/storage/message_filter_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _channel = 'chan1';
const _chat = [
'Good morning everyone',
'Anyone hearing the repeater on the hill today?',
'I just got back from the hike, signal was great',
'Testing from the north side of town',
'Thanks for the advert, I can see you now',
'How many hops is your path to the city?',
'Weather looks rough tonight, stay safe',
'My battery is at 40 percent after two days',
'Who is running the new solar node?',
'Copy that, heard you loud and clear',
'Is the meetup still on for Saturday?',
'Yes, 10am at the library parking lot',
'I moved my antenna higher, let me know if it helps',
'Reception improved a lot, thanks',
'Lunch break, back in an hour',
'Does anyone have a spare LoRa board to lend?',
'Ping from the coffee shop downtown',
'See you all tomorrow',
'Happy birthday Carol!',
'Can someone check if my messages are getting through?',
];
void main() {
late DateTime now;
late MessageFilterService service;
Future<MessageFilterService> create() async {
final s = MessageFilterService(
store: MessageFilterStore(),
clock: () => now,
);
await s.load();
return s;
}
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
now = DateTime(2026, 1, 1, 12);
service = await create();
});
FilterVerdict? eval(
String sender,
String text, {
String channel = _channel,
}) => service.evaluate(channelId: channel, sender: sender, text: text);
test('defaults: enabled, nothing filtered for normal chat', () {
expect(service.settings.enabled, isTrue);
expect(service.settings.displayMode, FilterDisplayMode.placeholder);
expect(service.isChannelFiltered(_channel), isTrue);
expect(eval('Bob', 'hello there'), isNull);
});
test('no implicit clean examples from excluded channels', () async {
await service.setChannelExcluded('ads', true);
final before = service.recentCleanCount;
service.recordClean(
channelId: 'ads',
sender: 'Bot',
text: 'Buy cheap radios today at the store',
);
expect(service.recentCleanCount, before);
service.recordClean(
channelId: _channel,
sender: 'Sam',
text: 'Anyone on the hill repeater tonight?',
);
expect(service.recentCleanCount, before + 1);
});
test('ruleVerdict matches rules without recording duplicates', () async {
await service.addRule(const FilterRule(id: 'r', pattern: 'meshos'));
expect(
service
.ruleVerdict(channelId: _channel, sender: 'a', text: 'get meshos')
?.reason,
FilterReason.textRule,
);
expect(
service.ruleVerdict(channelId: _channel, sender: 'a', text: 'hello'),
isNull,
);
await service.setChannelExcluded('off', true);
expect(
service.ruleVerdict(channelId: 'off', sender: 'a', text: 'get meshos'),
isNull,
);
// Nothing was recorded: the first real arrival is not a repeat.
const text = 'meet at the old fire tower at noon';
for (var i = 0; i < 3; i++) {
service.ruleVerdict(channelId: _channel, sender: 'a', text: text);
}
expect(eval('a', text), isNull);
});
test('skips outgoing, reactions, payloads, disabled and excluded', () async {
await service.addRule(
FilterRule(id: MessageFilterService.newRuleId(), pattern: 'bad'),
);
expect(
service.evaluate(
channelId: _channel,
sender: 'me',
text: 'bad',
isOutgoing: true,
),
isNull,
);
expect(
service.evaluate(
channelId: _channel,
sender: 'a',
text: 'bad',
isReaction: true,
),
isNull,
);
expect(eval('a', 'g:bad-gif'), isNull);
expect(eval('a', 'm:bad'), isNull);
await service.setChannelExcluded(_channel, true);
expect(service.isChannelFiltered(_channel), isFalse);
expect(eval('a', 'bad'), isNull);
expect(eval('a', 'bad', channel: 'other')?.reason, FilterReason.textRule);
await service.setChannelExcluded(_channel, false);
await service.updateSettings(service.settings.copyWith(enabled: false));
expect(eval('a', 'bad'), isNull);
});
test(
'sender rules win over text rules; disabled rules are ignored',
() async {
await service.addRule(
const FilterRule(
id: 't',
pattern: 'promo',
field: FilterRuleField.text,
),
);
await service.addRule(
const FilterRule(
id: 's',
pattern: 'Spammer',
field: FilterRuleField.sender,
match: FilterRuleMatch.exact,
),
);
expect(
eval('spammer', 'promo time'),
const FilterVerdict(reason: FilterReason.senderRule, detail: 'Spammer'),
);
expect(
eval('Bob', 'big PROMO'),
const FilterVerdict(reason: FilterReason.textRule, detail: 'promo'),
);
await service.updateRule(
const FilterRule(id: 't', pattern: 'promo', enabled: false),
);
expect(eval('Bob', 'another promo'), isNull);
await service.removeRule('s');
expect(service.rules.map((r) => r.id), ['t']);
},
);
test('repeated characters, togglable', () async {
expect(eval('a', 'n${'o' * 20}')?.reason, FilterReason.repeatedCharacters);
expect(eval('a', 'nooooooooo'), isNull);
await service.updateSettings(
service.settings.copyWith(repeatedCharacters: false),
);
expect(eval('b', 'ye${'s' * 20}'), isNull);
});
test('duplicates: same sender and cross sender', () {
expect(eval('a', 'meet at the park'), isNull);
now = now.add(const Duration(minutes: 2));
expect(
eval('a', 'Meet at the park!'),
const FilterVerdict(reason: FilterReason.duplicate),
);
const campaign = 'the meshcore trademark grab is theft, boycott him';
expect(eval('b', campaign), isNull);
expect(eval('d', campaign), isNull);
expect(eval('c', campaign)?.reason, FilterReason.crossSenderDuplicate);
// Short greetings from several senders are left alone.
expect(eval('e', 'Happy New Year!'), isNull);
expect(eval('f', 'Happy New Year!'), isNull);
expect(eval('g', 'Happy New Year!'), isNull);
});
test('duplicates setting off still records but does not filter', () async {
await service.updateSettings(service.settings.copyWith(duplicates: false));
expect(eval('a', 'meet at the park'), isNull);
expect(eval('a', 'meet at the park'), isNull);
await service.updateSettings(service.settings.copyWith(duplicates: true));
expect(eval('a', 'meet at the park')?.reason, FilterReason.duplicate);
});
test('rule-filtered texts are still recorded for duplicates', () async {
await service.addRule(const FilterRule(id: 'x', pattern: 'buy'));
expect(
eval('a', 'buy cheap radios here now')?.reason,
FilterReason.textRule,
);
await service.removeRule('x');
expect(
eval('a', 'buy cheap radios here now')?.reason,
FilterReason.duplicate,
);
});
test('not spam exempts duplicates in that channel', () async {
eval('a', 'meet at the park');
await service.markNotSpam(
channelId: _channel,
sender: 'a',
text: 'meet at the park',
);
expect(eval('a', 'meet at the park'), isNull);
expect(service.notSpamExampleCount, 1);
});
test('learning needs two spam taps, then catches similar promos', () async {
for (var i = 0; i < _chat.length; i++) {
service.recordClean(channelId: 'chat', sender: 'User$i', text: _chat[i]);
}
await service.markSpam(
sender: 'PromoBot',
text: 'Download MeshOS now! Free firmware at meshos.example',
);
expect(service.spamExampleCount, 1);
expect(
eval('X', 'Free MeshOS firmware download at meshos.example'),
isNull,
);
await service.markSpam(
sender: 'Deals',
text: 'Free MeshOS firmware upgrade, download at meshos.example now',
);
expect(service.spamExampleCount, 2);
expect(
eval('Y', 'Get free MeshOS firmware download now meshos.example')?.reason,
FilterReason.learned,
);
expect(eval('Z', 'Anyone on the hill repeater tonight?'), isNull);
await service.updateSettings(service.settings.copyWith(learning: false));
expect(
eval('W', 'Get the MeshOS firmware download free meshos.example'),
isNull,
);
});
test('marking spam twice for the same text keeps one example', () async {
await service.markSpam(sender: 'a', text: 'Buy now');
await service.markSpam(sender: 'a', text: 'buy NOW');
expect(service.spamExampleCount, 1);
await service.markNotSpam(
channelId: _channel,
sender: 'a',
text: 'buy now',
);
expect(service.spamExampleCount, 0);
expect(service.notSpamExampleCount, 1);
});
test('state persists across instances and reset keeps rules', () async {
await service.addRule(const FilterRule(id: 'r1', pattern: 'promo'));
await service.updateSettings(
service.settings.copyWith(displayMode: FilterDisplayMode.hide),
);
await service.markSpam(sender: 'a', text: 'spam one');
await service.markNotSpam(channelId: _channel, sender: 'b', text: 'hi');
final reloaded = await create();
expect(reloaded.rules.single.pattern, 'promo');
expect(reloaded.settings.displayMode, FilterDisplayMode.hide);
expect(reloaded.spamExampleCount, 1);
expect(reloaded.notSpamExampleCount, 1);
await reloaded.resetLearning();
expect(reloaded.spamExampleCount, 0);
expect(reloaded.notSpamExampleCount, 0);
expect(reloaded.rules, hasLength(1));
final again = await create();
expect(again.spamExampleCount, 0);
expect(again.rules, hasLength(1));
});
test('notifies listeners on changes', () async {
var count = 0;
service.addListener(() => count++);
await service.addRule(const FilterRule(id: 'n', pattern: 'x'));
await service.markSpam(sender: 'a', text: 'b');
await service.setChannelExcluded('c', true);
// addRule, markSpam (plus once more when its background training lands)
// and setChannelExcluded.
expect(count, 4);
});
test('addRule with index restores a deleted rule in place', () async {
for (final id in ['a', 'b', 'c']) {
await service.addRule(FilterRule(id: id, pattern: id));
}
final b = service.rules[1];
await service.removeRule('b');
await service.addRule(b, index: 1);
expect(service.rules.map((r) => r.id), ['a', 'b', 'c']);
await service.addRule(const FilterRule(id: 'z', pattern: 'z'), index: 99);
expect(service.rules.last.id, 'z');
});
test('newRuleId is unique', () {
final ids = List.generate(100, (_) => MessageFilterService.newRuleId());
expect(ids.toSet(), hasLength(100));
});
test(
'learning activates once clean examples arrive after spam taps',
() async {
// The first two messages received are the ones marked spam, so training
// has no clean examples yet and the classifier stays inactive.
await service.markSpam(
sender: 'PromoBot',
text: 'Download MeshOS now! Free firmware at meshos.example',
);
await service.markSpam(
sender: 'Deals',
text: 'Free MeshOS firmware upgrade, download at meshos.example now',
);
const probe = 'Get free MeshOS firmware download now meshos.example';
expect(eval('A', probe), isNull);
// Ordinary chat then arrives; no further taps.
for (var i = 0; i < _chat.length; i++) {
service.recordClean(
channelId: 'chat',
sender: 'User$i',
text: _chat[i],
);
}
await Future<void>.delayed(Duration.zero); // let the queued retrain start
await service.trainingSettled;
expect(eval('B', probe)?.reason, FilterReason.learned);
expect(eval('C', 'Anyone on the hill repeater tonight?'), isNull);
},
);
}
@@ -0,0 +1,165 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/services/message_filter/message_filter_text.dart';
FilterRule _rule(
String pattern, {
FilterRuleField field = FilterRuleField.text,
FilterRuleMatch match = FilterRuleMatch.contains,
}) => FilterRule(id: 'r', pattern: pattern, field: field, match: match);
void main() {
group('normalize', () {
test('lower-cases, collapses whitespace and trims', () {
expect(
MessageFilterText.normalize(' Hello \n\t WORLD '),
'hello world',
);
});
test('strips accents', () {
expect(MessageFilterText.normalize('Ça vá Ñoño Öl'), 'ca va nono ol');
// Decomposed form (combining marks).
expect(MessageFilterText.normalize('Café'), 'cafe');
});
test('maps Cyrillic and Greek look-alikes to Latin', () {
// Cyrillic М е о and Greek Ο.
expect(MessageFilterText.normalize('Мeshоs'), 'meshos');
expect(MessageFilterText.normalize('MeshΟS'), 'meshos');
});
test('removes zero-width and soft hyphen characters', () {
expect(MessageFilterText.normalize('me​sh‌‍o⁠s­'), 'meshos');
});
test('folds fullwidth and styled letters', () {
expect(MessageFilterText.normalize('MESH'), 'mesh');
expect(MessageFilterText.normalize('\u{1D400}\u{1D41B}'), 'ab');
});
});
group('normalizeForDuplicates', () {
test('drops mentions, punctuation and emoji', () {
expect(
MessageFilterText.normalizeForDuplicates('@[Bob] Hello, world!!! 😀'),
'hello world',
);
expect(
MessageFilterText.normalizeForDuplicates('Hello world'),
MessageFilterText.normalizeForDuplicates('hello... WORLD?'),
);
});
});
group('matchesRule', () {
test('contains', () {
final rule = _rule('MeshOS');
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'try meshos!'),
isTrue,
);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'mesh os'),
isFalse,
);
});
test('whole word uses unicode boundaries', () {
final rule = _rule('cat', match: FilterRuleMatch.wholeWord);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'my cat!'),
isTrue,
);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'Cat'),
isTrue,
);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'category'),
isFalse,
);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'catß'),
isFalse,
);
final phrase = _rule('free (offer)', match: FilterRuleMatch.wholeWord);
expect(
MessageFilterText.matchesRule(
phrase,
sender: 'a',
text: 'a FREE (offer) now',
),
isTrue,
);
});
test('exact', () {
final rule = _rule('hello', match: FilterRuleMatch.exact);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: ' HELLO '),
isTrue,
);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'hello there'),
isFalse,
);
});
test('respects the field', () {
final sender = _rule('spammer', field: FilterRuleField.sender);
expect(
MessageFilterText.matchesRule(sender, sender: 'Spammer', text: 'hi'),
isTrue,
);
expect(
MessageFilterText.matchesRule(sender, sender: 'bob', text: 'spammer'),
isFalse,
);
final both = _rule('spammer', field: FilterRuleField.both);
expect(
MessageFilterText.matchesRule(both, sender: 'bob', text: 'spammer'),
isTrue,
);
expect(
MessageFilterText.matchesRule(both, sender: 'SPAMMER', text: 'hi'),
isTrue,
);
});
test('empty pattern never matches', () {
expect(
MessageFilterText.matchesRule(_rule(' '), sender: 'a', text: 'b'),
isFalse,
);
});
});
test('repeated characters', () {
expect(MessageFilterText.hasRepeatedCharacters('a' * 20), isTrue);
expect(MessageFilterText.hasRepeatedCharacters('wow${'!' * 20}'), isTrue);
expect(
MessageFilterText.hasRepeatedCharacters('AAAAAAAAAA${'a' * 10}'),
isTrue,
);
expect(MessageFilterText.hasRepeatedCharacters('😀' * 20), isTrue);
expect(MessageFilterText.hasRepeatedCharacters('a' * 19), isFalse);
// Ordinary chat that the old 8-character threshold caught.
expect(MessageFilterText.hasRepeatedCharacters('Noooooooo!'), isFalse);
expect(MessageFilterText.hasRepeatedCharacters('-' * 12), isFalse);
expect(MessageFilterText.hasRepeatedCharacters('!!!!!!!!'), isFalse);
expect(MessageFilterText.hasRepeatedCharacters('😀' * 8), isFalse);
// Digit runs never count (frequencies, coordinates, ids).
expect(MessageFilterText.hasRepeatedCharacters('0' * 30), isFalse);
expect(
MessageFilterText.hasRepeatedCharacters('hello there'),
isFalse,
);
});
test('structured payloads', () {
expect(MessageFilterText.isStructuredPayload('g:abc'), isTrue);
expect(MessageFilterText.isStructuredPayload(' m:xyz'), isTrue);
expect(MessageFilterText.isStructuredPayload('good morning'), isFalse);
});
}
@@ -0,0 +1,149 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/services/message_filter/ngram_spam_classifier.dart';
FilterExample _ex(String sender, String text) =>
FilterExample(sender: sender, text: text, addedAtMs: 0);
final _spam = [
_ex(
'PromoBot',
'Download MeshOS now! Free firmware upgrade at meshos.example',
),
_ex(
'MeshDeals',
'FREE upgrade!!! Get MeshOS firmware today, visit meshos.example',
),
_ex(
'PromoBot',
'Best firmware ever: MeshOS. Download free at meshos.example now',
),
_ex('Promo2', 'Limited offer: MeshOS firmware download free, meshos.example'),
_ex(
'MeshDeals',
'Upgrade your node with MeshOS! Free download at meshos.example',
),
_ex('Promo3', 'Get the free MeshOS firmware now - meshos.example download'),
];
final _ham = [
_ex('Alice', 'Good morning everyone'),
_ex('Bob', 'Anyone hearing the repeater on the hill today?'),
_ex('Carol', 'I just got back from the hike, signal was great'),
_ex('Dave', 'Testing from the north side of town'),
_ex('Alice', 'Thanks for the advert, I can see you now'),
_ex('Eve', 'How many hops is your path to the city?'),
_ex('Bob', 'Weather looks rough tonight, stay safe'),
_ex('Frank', 'My battery is at 40 percent after two days'),
_ex('Carol', 'Who is running the new solar node?'),
_ex('Dave', 'Copy that, heard you loud and clear'),
_ex('Grace', 'Is the meetup still on for Saturday?'),
_ex('Heidi', 'Yes, 10am at the library parking lot'),
_ex('Ivan', 'I moved my antenna higher, let me know if it helps'),
_ex('Judy', 'Reception improved a lot, thanks'),
_ex('Alice', 'Lunch break, back in an hour'),
_ex('Bob', 'Does anyone have a spare LoRa board to lend?'),
_ex('Frank', 'Ping from the coffee shop downtown'),
_ex('Grace', 'See you all tomorrow'),
_ex('Eve', 'The traffic on the highway is terrible right now'),
_ex('Heidi', 'Happy birthday Carol!'),
_ex('Ivan', 'Can someone check if my messages are getting through?'),
_ex('Judy', 'Got it, three hops via the hill repeater'),
_ex('Carol', 'Thank you all, great community here'),
_ex('Dave', 'Power is out in my area, running on battery'),
_ex('Alice', 'Nice sunset from the ridge'),
_ex('Bob', 'Updating my node settings, brb'),
_ex('Eve', 'Good night folks'),
_ex('Frank', 'Anyone near the river trail?'),
_ex('Grace', 'The new channel works well for our group'),
_ex('Heidi', 'Is there a map of the repeaters somewhere?'),
];
void main() {
test('untrained classifier returns 0', () {
final classifier = NgramSpamClassifier();
expect(classifier.isTrained, isFalse);
expect(classifier.probability('x', 'anything'), 0.0);
});
test('needs both classes to train', () {
final classifier = NgramSpamClassifier()..train(_spam, const []);
expect(classifier.isTrained, isFalse);
});
test('FNV-1a 32 matches reference vectors', () {
expect(NgramSpamClassifier.fnv1a32(''), 0x811C9DC5);
expect(NgramSpamClassifier.fnv1a32('a'), 0xE40C292C);
expect(NgramSpamClassifier.fnv1a32('foobar'), 0xBF9CF968);
});
test('feature strings include char n-grams, words, bigrams, sender', () {
final features = NgramSpamClassifier.featureStrings('Bob', 'Hi there');
expect(features, contains('c: hi '));
expect(features, contains('c: th'));
expect(features, contains('c:there'));
expect(features, contains('w:there'));
expect(features, contains('b:hi there'));
expect(features, contains('s:bob'));
});
test('scores held-out promo high and ordinary chat low', () {
final classifier = NgramSpamClassifier()..train(_spam, _ham);
expect(classifier.isTrained, isTrue);
final promo = classifier.probability(
'NewPromo',
'Free MeshOS firmware download now at meshos.example!',
);
expect(promo, greaterThanOrEqualTo(0.8));
for (final text in [
'Anyone on the hill repeater tonight?',
'Good morning, heading out for a hike',
'My node battery lasted three days',
'See you at the meetup on Saturday',
]) {
expect(classifier.probability('Zoe', text), lessThan(0.5), reason: text);
}
});
test('look-alike characters do not dodge the classifier', () {
final classifier = NgramSpamClassifier()..train(_spam, _ham);
// Cyrillic "е"/"о" and a zero-width space.
final p = classifier.probability(
'NewPromo',
'Frеe MeshОS firm​ware download now at meshos.example',
);
expect(p, greaterThanOrEqualTo(0.8));
});
test('training is deterministic', () {
final a = NgramSpamClassifier()..train(_spam, _ham);
final b = NgramSpamClassifier()..train(_spam, _ham);
const text = 'free firmware download';
expect(a.probability('x', text), b.probability('x', text));
});
test('trains 500 documents quickly', () {
final spam = <FilterExample>[];
final ham = <FilterExample>[];
for (var i = 0; i < 200; i++) {
final s = _spam[i % _spam.length];
spam.add(_ex('${s.sender}$i', '${s.text} code $i'));
}
for (var i = 0; i < 300; i++) {
final h = _ham[i % _ham.length];
ham.add(_ex('${h.sender}$i', '${h.text} number $i'));
}
final classifier = NgramSpamClassifier();
// Warm up the JIT once, then measure.
classifier.train(spam.take(20).toList(), ham.take(20).toList());
final stopwatch = Stopwatch()..start();
classifier.train(spam, ham);
stopwatch.stop();
expect(classifier.isTrained, isTrue);
expect(stopwatch.elapsedMilliseconds, lessThan(500));
// ignore: avoid_print
print('Trained 500 docs in ${stopwatch.elapsedMilliseconds} ms');
});
}
+104
View File
@@ -0,0 +1,104 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/storage/message_filter_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<void> _init(Map<String, Object> values) async {
SharedPreferences.setMockInitialValues(values);
PrefsManager.reset();
await PrefsManager.initialize();
}
void main() {
test('empty prefs load defaults', () async {
await _init({});
final store = MessageFilterStore();
final settings = store.loadSettings();
expect(settings.enabled, isTrue);
expect(settings.displayMode, FilterDisplayMode.placeholder);
expect(settings.duplicates, isTrue);
expect(settings.repeatedCharacters, isTrue);
expect(settings.learning, isTrue);
expect(settings.excludedChannelIds, isEmpty);
expect(store.loadRules(), isEmpty);
expect(store.loadSpamExamples(), isEmpty);
expect(store.loadHamExamples(), isEmpty);
expect(store.loadRecentClean(), isEmpty);
});
test('round-trips settings, rules and examples', () async {
await _init({});
final store = MessageFilterStore();
await store.saveSettings(
const MessageFilterSettings(
enabled: false,
displayMode: FilterDisplayMode.hide,
duplicates: false,
repeatedCharacters: false,
learning: false,
excludedChannelIds: {'a', 'slot:3'},
),
);
await store.saveRules(const [
FilterRule(
id: '1',
pattern: 'MeshOS',
field: FilterRuleField.both,
match: FilterRuleMatch.wholeWord,
enabled: false,
),
]);
const example = FilterExample(sender: 's', text: 't', addedAtMs: 42);
await store.saveSpamExamples(const [example]);
await store.saveHamExamples(const [example, example]);
await store.saveRecentClean(const [example]);
final settings = store.loadSettings();
expect(settings.enabled, isFalse);
expect(settings.displayMode, FilterDisplayMode.hide);
expect(settings.duplicates, isFalse);
expect(settings.repeatedCharacters, isFalse);
expect(settings.learning, isFalse);
expect(settings.excludedChannelIds, {'a', 'slot:3'});
expect(store.loadRules(), const [
FilterRule(
id: '1',
pattern: 'MeshOS',
field: FilterRuleField.both,
match: FilterRuleMatch.wholeWord,
enabled: false,
),
]);
final spam = store.loadSpamExamples().single;
expect((spam.sender, spam.text, spam.addedAtMs), ('s', 't', 42));
expect(store.loadHamExamples(), hasLength(2));
expect(store.loadRecentClean(), hasLength(1));
});
test('tolerates malformed data', () async {
await _init({
MessageFilterStore.settingsKey: '{not json',
MessageFilterStore.rulesKey:
'[{"id":"1","pattern":"ok","field":"weird","match":"nope"}, 5, '
'{"id":"","pattern":"x"}]',
MessageFilterStore.spamExamplesKey: '{"a":1}',
});
final store = MessageFilterStore();
expect(store.loadSettings().enabled, isTrue);
final rule = store.loadRules().single;
expect(rule.pattern, 'ok');
expect(rule.field, FilterRuleField.text);
expect(rule.match, FilterRuleMatch.contains);
expect(rule.enabled, isTrue);
expect(store.loadSpamExamples(), isEmpty);
});
test('filter reason json helpers', () {
for (final reason in FilterReason.values) {
expect(filterReasonFromJson(filterReasonToJson(reason)), reason);
}
expect(filterReasonFromJson(null), isNull);
expect(filterReasonFromJson('unknown'), isNull);
});
}
@@ -0,0 +1,265 @@
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/l10n/app_localizations_en.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/widgets/filtered_message_ghost.dart';
Future<void> _pump(WidgetTester tester, Widget child) {
return tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(body: ListView(children: [child])),
),
);
}
void main() {
group('FilteredMessageGhost', () {
testWidgets('single message: copy, reason, tap target', (tester) async {
var taps = 0;
await _pump(
tester,
FilteredMessageGhost(
count: 1,
reason: 'Filtered: repeated message',
onTap: () => taps++,
),
);
expect(find.text('Hidden message · Tap to view'), findsOneWidget);
expect(find.text('Filtered: repeated message'), findsOneWidget);
expect(find.byIcon(Icons.visibility_off_outlined), findsOneWidget);
expect(find.byTooltip('Hidden by your message filter'), findsOneWidget);
final inkWell = find.byType(InkWell);
expect(tester.getSize(inkWell).height, greaterThanOrEqualTo(48));
await tester.tap(find.byType(FilteredMessageGhost));
expect(taps, 1);
});
testWidgets('expanded header offers one-tap collapse', (tester) async {
var taps = 0;
await _pump(
tester,
FilteredMessageGhost(
count: 4,
reason: 'Filtered: repeated message',
expanded: true,
onTap: () => taps++,
),
);
expect(
find.text('Showing 4 hidden messages · Tap to hide'),
findsOneWidget,
);
expect(find.byIcon(Icons.expand_less), findsOneWidget);
expect(find.byIcon(Icons.visibility_off_outlined), findsNothing);
await tester.tap(find.byType(FilteredMessageGhost));
expect(taps, 1);
await _pump(
tester,
FilteredMessageGhost(
count: 1,
reason: 'Filtered: repeated message',
expanded: true,
onTap: () {},
),
);
expect(find.text('Showing hidden message · Tap to hide'), findsOneWidget);
});
testWidgets('run: plural copy and semantics label', (tester) async {
final handle = tester.ensureSemantics();
await _pump(
tester,
FilteredMessageGhost(
count: 3,
reason: 'Filtered: repeated characters',
onTap: () {},
),
);
expect(find.text('3 hidden messages · Tap to view'), findsOneWidget);
expect(
find.bySemanticsLabel(
'3 hidden messages · Tap to view. Filtered: repeated characters',
),
findsOneWidget,
);
expect(
tester.getSemantics(find.byType(FilteredMessageGhost)),
matchesSemantics(
isButton: true,
hasTapAction: true,
label:
'3 hidden messages · Tap to view. Filtered: repeated characters',
),
);
handle.dispose();
});
testWidgets('screen-reader tap reveals the run', (tester) async {
final handle = tester.ensureSemantics();
var taps = 0;
await _pump(
tester,
FilteredMessageGhost(count: 2, reason: 'r', onTap: () => taps++),
);
final node = tester.getSemantics(find.byType(FilteredMessageGhost));
node.owner!.performAction(node.id, SemanticsAction.tap);
expect(taps, 1);
handle.dispose();
});
testWidgets('grows with the chat text scale', (tester) async {
await _pump(
tester,
FilteredMessageGhost(count: 1, reason: 'r', onTap: () {}),
);
final small = tester.getSize(find.byType(InkWell)).height;
await _pump(
tester,
FilteredMessageGhost(count: 1, reason: 'r', textScale: 2, onTap: () {}),
);
final large = tester.getSize(find.byType(InkWell)).height;
expect(large, greaterThan(small));
});
});
group('FilteredMessageBanner', () {
testWidgets('shows the reason and both actions', (tester) async {
var notSpam = 0;
var hide = 0;
await _pump(
tester,
FilteredMessageBanner(
reason: 'Filtered: you marked this as spam',
color: Colors.black,
onNotSpam: () => notSpam++,
onHide: () => hide++,
),
);
expect(find.text('Filtered: you marked this as spam'), findsOneWidget);
await tester.tap(find.text('Not spam'));
await tester.tap(find.text('Hide'));
expect(notSpam, 1);
expect(hide, 1);
for (final label in ['Not spam', 'Hide']) {
final button = find.ancestor(
of: find.text(label),
matching: find.byType(TextButton),
);
expect(tester.getSize(button).height, greaterThanOrEqualTo(48));
}
});
});
test('messageFilterReasonLabel covers every reason', () {
final l10n = AppLocalizationsEn();
expect(
messageFilterReasonLabel(l10n, 'textRule', 'meshos'),
'Filtered: matches "meshos"',
);
expect(
messageFilterReasonLabel(l10n, 'senderRule', 'Bot'),
'Filtered: sender "Bot"',
);
expect(
messageFilterReasonLabel(l10n, 'crossSenderDuplicate', null),
'Filtered: same message from several senders',
);
expect(
messageFilterReasonLabel(l10n, 'unknown-reason', null),
'Filtered: you marked this as spam',
);
final longPattern = 'Buy cheap radios now at example dot com today';
final label = messageFilterReasonLabel(l10n, 'textRule', longPattern);
expect(label, isNot(contains(longPattern)));
expect(label, 'Filtered: matches "Buy cheap radios now at…"');
expect(shortFilterDetail('a\n b'), 'a b');
for (final reason in FilterReason.values) {
expect(
messageFilterReasonLabel(l10n, filterReasonToJson(reason), 'x'),
startsWith('Filtered:'),
);
}
});
group('FilteredMessageRun', () {
Widget run({required bool expanded, bool reduceMotion = false}) {
return MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: MediaQuery(
data: MediaQueryData(disableAnimations: reduceMotion),
child: Scaffold(
body: ListView(
children: [
FilteredMessageRun(
count: 2,
reason: 'Filtered: repeated message',
expanded: expanded,
onToggle: () {},
buildMessages: (_) => const [
SizedBox(height: 60, child: Text('first copy')),
SizedBox(height: 60, child: Text('second copy')),
],
),
],
),
),
),
);
}
double bodyHeight(WidgetTester tester) =>
tester.getSize(find.byType(FilteredMessageRun)).height -
tester.getSize(find.byType(FilteredMessageGhost)).height;
testWidgets('animates open and closed in place', (tester) async {
await tester.pumpWidget(run(expanded: false));
expect(find.text('first copy'), findsNothing);
expect(bodyHeight(tester), 0);
await tester.pumpWidget(run(expanded: true));
await tester.pump(filteredRunAnimationDuration ~/ 2);
final midOpen = bodyHeight(tester);
expect(midOpen, greaterThan(0));
expect(midOpen, lessThan(120));
await tester.pumpAndSettle();
expect(bodyHeight(tester), closeTo(120, 0.01));
expect(find.text('first copy'), findsOneWidget);
expect(
find.text('Showing 2 hidden messages · Tap to hide'),
findsOneWidget,
);
await tester.pumpWidget(run(expanded: false));
await tester.pump(filteredRunAnimationDuration ~/ 2);
final midClose = bodyHeight(tester);
expect(midClose, greaterThan(0));
expect(midClose, lessThan(120));
await tester.pumpAndSettle();
expect(find.text('first copy'), findsNothing);
expect(bodyHeight(tester), 0);
});
testWidgets('reduced motion switches instantly', (tester) async {
await tester.pumpWidget(run(expanded: false, reduceMotion: true));
await tester.pumpWidget(run(expanded: true, reduceMotion: true));
await tester.pump();
expect(bodyHeight(tester), closeTo(120, 0.01));
await tester.pumpWidget(run(expanded: false, reduceMotion: true));
await tester.pump();
expect(bodyHeight(tester), 0);
});
});
}