Fix mobile unread state retaining deleted messages (#8883)

This commit is contained in:
klopez4212
2026-11-01 18:51:20 +00:00
committed by GitHub
parent e18d422d72
commit 21a9839826
7 changed files with 493 additions and 188 deletions

View File

@@ -555,13 +555,17 @@ String _encodeRootIdSet(Set<String> values) => jsonEncode(values.toList());
/// ceiling enforced by `just file-size-check`. Private members stay reachable:
/// a part shares its parent's library.
extension _ObservedUnreadRecording on ChannelsNotifier {
void _recordUnreadEvent(
bool _recordUnreadEvent(
Channel channel,
NostrEvent event,
String myPk, {
bool countQuiet = false,
}) {
if (!countQuiet && isQuietAgentMessage(event.tags)) return;
if (_unscopedUnreadDeletedIds.contains(event.id) ||
_unreadDeletedIdsByChannel[channel.id]?.contains(event.id) == true) {
return false;
}
if (!countQuiet && isQuietAgentMessage(event.tags)) return false;
// A counted quiet event is only a backlog marker: it never earns attention
// through its mentions or thread.
final isThreadedReply =
@@ -588,5 +592,6 @@ extension _ObservedUnreadRecording on ChannelsNotifier {
if (event.createdAt > current) {
_latestObservedByChannel[channel.id] = event.createdAt;
}
return true;
}
}

View File

@@ -0,0 +1,182 @@
part of 'channels_provider.dart';
extension _UnreadCatchUp on ChannelsNotifier {
/// Backfills unread badges for the channels this refresh just installed.
///
/// Runs detached from the refresh that starts it, so the lifecycle token
/// captured below is what keeps a response that outlived its refresh from
/// writing unread state into whatever the user is looking at now. Every
/// refresh path starts a catch-up, including the initial load, the ordinary
/// membership refresh a join performs and the reconnect backstop, so the
/// token is unconditional rather than tied to discovery. A retired refresh
/// returns instead of throwing: nothing awaits this future, so a thrown
/// [_StaleChannelRefresh] would only surface as an unhandled error.
///
/// The request fence and subscription generation are passed from the refresh
/// that installed [channels], preserving request ownership after detachment.
Future<void> _catchUpUnreadEvents(
List<Channel> channels,
_ChannelRefreshFence fence,
int subscriptionGeneration,
) async {
if (!_lifecycleRef.mounted) return;
try {
final myPk = _lifecycleRef.read(myPubkeyProvider);
if (myPk == null) return;
final session = _lifecycleRef.read(relaySessionProvider.notifier);
final mutedChannelIds = _mutedChannelIds();
final readState = _lifecycleRef.read(readStateProvider);
final activeChannels = [
for (final channel in channels)
if (channel.isMember && !channel.isArchived) channel,
];
final channelById = {
for (final channel in activeChannels) channel.id: channel,
};
final readAtByChannel = {
for (final channel in activeChannels)
channel.id: readState.effectiveTimestamp(channel.id),
};
final filters = [
for (final channel in activeChannels)
for (final kinds in [
EventKind.channelMessageEventKinds,
[EventKind.deletion, EventKind.nip29DeleteEvent],
])
NostrFilter(
kinds: kinds,
tags: {
'#h': [channel.id],
},
since: (readAtByChannel[channel.id] ?? -1) + 1,
limit: _unreadCatchUpLimit,
),
];
final events = await _fetchChannelHistoryBatch(
session,
filters,
operation: 'unread catch-up',
);
// Unavailable: keep the unread state already observed.
if (events == null) return;
// The relay round-trip above is the window Jed's probes park in: a newer
// refresh, a community switch or an identity switch here means every
// write below belongs to a channel list the user has left.
if (!_lifecycleRef.mounted ||
_isCatchUpRetired(fence, subscriptionGeneration)) {
return;
}
// Keep this response's deletion evidence independently of the bounded
// cross-request tombstones: a large batch can evict its own early IDs.
final batchDeletedIds = <String>{};
var appliedDeletion = false;
for (final event in events) {
final channelId = event.channelId;
if (channelById.containsKey(channelId) ||
(channelId == null && event.kind == EventKind.deletion)) {
if (_applyUnreadDeletion(event)) {
appliedDeletion = true;
batchDeletedIds.addAll(
event.tags
.where((tag) => tag.length >= 2 && tag[0] == 'e')
.map((tag) => tag[1]),
);
}
}
}
for (final event in events) {
if (batchDeletedIds.contains(event.id)) continue;
if (EventKind.channelMessageEventKinds.contains(event.kind) &&
event.pubkey.toLowerCase() == myPk.toLowerCase()) {
_recordSelfThreadInterest(event, myPk);
}
}
final recordedAtByChannel = <String, int>{};
final windowSizeByChannel = <String, int>{};
final oldestQuietByChannel = <String, NostrEvent>{};
for (final event in events) {
if (!EventKind.channelMessageEventKinds.contains(event.kind)) continue;
final channelId = event.channelId;
if (channelId == null) continue;
final channel = channelById[channelId];
if (channel == null) continue;
windowSizeByChannel.update(channelId, (n) => n + 1, ifAbsent: () => 1);
if (batchDeletedIds.contains(event.id) ||
_unscopedUnreadDeletedIds.contains(event.id) ||
_unreadDeletedIdsByChannel[channelId]?.contains(event.id) == true) {
continue;
}
final readAt = readAtByChannel[channelId];
if (event.pubkey.toLowerCase() == myPk.toLowerCase()) continue;
if (readAt != null && event.createdAt <= readAt) continue;
if (!shouldNotifyForEvent(
event,
myPk,
participatedRootIds: _participatedRootIds,
followedRootIds: _followedRootIds(),
authoredRootIds: _authoredRootIds,
mutedChannelIds: mutedChannelIds,
channelId: channel.id,
)) {
continue;
}
if (isQuietAgentMessage(event.tags)) {
final oldest = oldestQuietByChannel[channelId];
if (oldest == null || event.createdAt < oldest.createdAt) {
oldestQuietByChannel[channelId] = event;
}
continue;
}
if (!_recordUnreadEvent(channel, event, myPk)) continue;
recordedAtByChannel[channelId] = max(
recordedAtByChannel[channelId] ?? 0,
event.createdAt,
);
}
// A full window of quiet agent messages can hide an older unread event,
// and every refresh asks for the same window. Count its oldest quiet
// message instead, so the channel stays unread until it is opened.
for (final MapEntry(key: channelId, value: quiet)
in oldestQuietByChannel.entries) {
if (recordedAtByChannel.containsKey(channelId)) continue;
if ((windowSizeByChannel[channelId] ?? 0) < _unreadCatchUpLimit) {
continue;
}
if (_recordUnreadEvent(
channelById[channelId]!,
quiet,
myPk,
countQuiet: true,
)) {
recordedAtByChannel[channelId] = quiet.createdAt;
}
}
// Republish only when this catch-up actually changed unread state. A
// batch that recorded nothing has nothing to show, and a failed or
// superseded batch must not repaint another refresh's list: the retired
// check above already returned in that case, and no await separates it
// from here, so a second check would be dead code.
// Recorded events also advance `lastMessageAt`, as live events do: a
// deadline-unavailable latest-message batch leaves it unset.
if (recordedAtByChannel.isNotEmpty || appliedDeletion) {
_publishUnreadCatchUp(recordedAtByChannel);
}
} catch (error) {
if (!_lifecycleRef.mounted) return;
debugPrint('[ChannelsNotifier] unread catch-up failed: $error');
} finally {
// Optional history can terminate without data. Release this destination
// with its retained unread state, but never settle a retired request.
if (_lifecycleRef.mounted &&
!_isCatchUpRetired(fence, subscriptionGeneration)) {
_settledUnreadGeneration = subscriptionGeneration;
_notifyUnreadReadinessChanged();
}
}
}
}

View File

@@ -0,0 +1,45 @@
part of 'channels_provider.dart';
/// Apply the same authenticated relay deletion evidence as the timeline.
/// Keep bounded tombstones so an in-flight history response cannot restore a
/// deleted mention after the live deletion has removed it from unread state.
extension _UnreadDeletions on ChannelsNotifier {
bool _applyUnreadDeletion(NostrEvent event) {
if (event.kind != EventKind.deletion &&
event.kind != EventKind.nip29DeleteEvent) {
return false;
}
final channelId = event.channelId;
if (channelId == null && event.kind != EventKind.deletion) return false;
// NIP-09 can omit h: the relay scopes the event using its target's stored
// channel. Event IDs are globally unique, so retain those targets across
// this community until their messages arrive, without guessing a channel.
final deleted = channelId == null
? _unscopedUnreadDeletedIds
: _unreadDeletedIdsByChannel.putIfAbsent(channelId, () => {});
final targets = {
for (final tag in event.tags)
if (tag.length >= 2 && tag[0] == 'e') tag[1],
};
deleted.addAll(targets);
while (deleted.length > _unreadCatchUpLimit) {
deleted.remove(deleted.first);
}
final channels = channelId == null
? _observedUnreadEventsByChannel.keys.toList()
: [channelId];
for (final id in channels) {
final observed = _observedUnreadEventsByChannel[id];
observed?.removeWhere((key, _) => targets.contains(key));
if (observed == null || observed.isEmpty) {
_observedUnreadEventsByChannel.remove(id);
_latestObservedByChannel.remove(id);
} else {
_latestObservedByChannel[id] = observed.values
.map((event) => event.createdAt)
.reduce(max);
}
}
return true;
}
}

View File

@@ -24,6 +24,8 @@ import 'unread_badge/observed_unread_event.dart';
import 'unread_badge/should_notify_for_event.dart';
part 'channel_directory.dart';
part 'channel_unread_deletions.dart';
part 'channel_unread_catch_up.dart';
part 'channel_snapshot.dart';
part 'channel_member_snapshots.dart';
part 'channels_provider_lifecycle.dart';
@@ -63,6 +65,8 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
final Map<String, int> _latestObservedByChannel = {};
final Map<String, Map<String, ObservedUnreadEvent>>
_observedUnreadEventsByChannel = {};
final Map<String, Set<String>> _unreadDeletedIdsByChannel = {};
final Set<String> _unscopedUnreadDeletedIds = {};
Set<String> _participatedRootIds = {};
Set<String> _authoredRootIds = {};
String? _threadInterestPubkey;
@@ -237,6 +241,8 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
_clearLiveSubscriptions();
_latestObservedByChannel.clear();
_observedUnreadEventsByChannel.clear();
_unreadDeletedIdsByChannel.clear();
_unscopedUnreadDeletedIds.clear();
_backstopTimer?.cancel();
_backstopTimer = null;
});
@@ -736,154 +742,13 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
);
}
/// Backfills unread badges for the channels this refresh just installed.
///
/// Runs detached from the refresh that starts it, so the lifecycle token
/// captured below is what keeps a response that outlived its refresh from
/// writing unread state into whatever the user is looking at now. Every
/// refresh path starts a catch-up, including the initial load, the ordinary
/// membership refresh a join performs and the reconnect backstop, so the
/// token is unconditional rather than tied to discovery. A retired refresh
/// returns instead of throwing: nothing awaits this future, so a thrown
/// [_StaleChannelRefresh] would only surface as an unhandled error.
///
/// The request fence and subscription generation are passed from the refresh
/// that installed [channels], preserving request ownership after detachment.
Future<void> _catchUpUnreadEvents(
List<Channel> channels,
_ChannelRefreshFence fence,
int subscriptionGeneration,
) async {
if (!ref.mounted) return;
try {
final myPk = ref.read(myPubkeyProvider);
if (myPk == null) return;
final session = ref.read(relaySessionProvider.notifier);
final mutedChannelIds = _mutedChannelIds();
final readState = ref.read(readStateProvider);
final activeChannels = [
void _publishUnreadCatchUp(Map<String, int> recordedAtByChannel) {
state = state.whenData(
(channels) => [
for (final channel in channels)
if (channel.isMember && !channel.isArchived) channel,
];
final channelById = {
for (final channel in activeChannels) channel.id: channel,
};
final readAtByChannel = {
for (final channel in activeChannels)
channel.id: readState.effectiveTimestamp(channel.id),
};
final filters = [
for (final channel in activeChannels)
NostrFilter(
kinds: EventKind.channelMessageEventKinds,
tags: {
'#h': [channel.id],
},
since: (readAtByChannel[channel.id] ?? -1) + 1,
limit: _unreadCatchUpLimit,
),
];
final events = await _fetchChannelHistoryBatch(
session,
filters,
operation: 'unread catch-up',
);
// Unavailable: keep the unread state already observed.
if (events == null) return;
// The relay round-trip above is the window Jed's probes park in: a newer
// refresh, a community switch or an identity switch here means every
// write below belongs to a channel list the user has left.
if (!ref.mounted || _isCatchUpRetired(fence, subscriptionGeneration)) {
return;
}
for (final event in events) {
if (event.pubkey.toLowerCase() == myPk.toLowerCase()) {
_recordSelfThreadInterest(event, myPk);
}
}
final recordedAtByChannel = <String, int>{};
final windowSizeByChannel = <String, int>{};
final oldestQuietByChannel = <String, NostrEvent>{};
for (final event in events) {
final channelId = event.channelId;
if (channelId == null) continue;
final channel = channelById[channelId];
if (channel == null) continue;
windowSizeByChannel.update(channelId, (n) => n + 1, ifAbsent: () => 1);
final readAt = readAtByChannel[channelId];
if (event.pubkey.toLowerCase() == myPk.toLowerCase()) continue;
if (readAt != null && event.createdAt <= readAt) continue;
if (!shouldNotifyForEvent(
event,
myPk,
participatedRootIds: _participatedRootIds,
followedRootIds: _followedRootIds(),
authoredRootIds: _authoredRootIds,
mutedChannelIds: mutedChannelIds,
channelId: channel.id,
)) {
continue;
}
if (isQuietAgentMessage(event.tags)) {
final oldest = oldestQuietByChannel[channelId];
if (oldest == null || event.createdAt < oldest.createdAt) {
oldestQuietByChannel[channelId] = event;
}
continue;
}
_recordUnreadEvent(channel, event, myPk);
recordedAtByChannel[channelId] = max(
recordedAtByChannel[channelId] ?? 0,
event.createdAt,
);
}
// A full window of quiet agent messages can hide an older unread event,
// and every refresh asks for the same window. Count its oldest quiet
// message instead, so the channel stays unread until it is opened.
for (final MapEntry(key: channelId, value: quiet)
in oldestQuietByChannel.entries) {
if (recordedAtByChannel.containsKey(channelId)) continue;
if ((windowSizeByChannel[channelId] ?? 0) < _unreadCatchUpLimit) {
continue;
}
_recordUnreadEvent(
channelById[channelId]!,
quiet,
myPk,
countQuiet: true,
);
recordedAtByChannel[channelId] = quiet.createdAt;
}
// Republish only when this catch-up actually changed unread state. A
// batch that recorded nothing has nothing to show, and a failed or
// superseded batch must not repaint another refresh's list: the retired
// check above already returned in that case, and no await separates it
// from here, so a second check would be dead code.
// Recorded events also advance `lastMessageAt`, as live events do: a
// deadline-unavailable latest-message batch leaves it unset.
if (recordedAtByChannel.isNotEmpty) {
state = state.whenData(
(channels) => [
for (final channel in channels)
_advanceLastMessageAt(channel, recordedAtByChannel[channel.id]),
],
);
}
} catch (error) {
if (!ref.mounted) return;
debugPrint('[ChannelsNotifier] unread catch-up failed: $error');
} finally {
// Optional history can terminate without data. Release this destination
// with its retained unread state, but never settle a retired request.
if (ref.mounted && !_isCatchUpRetired(fence, subscriptionGeneration)) {
_settledUnreadGeneration = subscriptionGeneration;
_notifyUnreadReadinessChanged();
}
}
_advanceLastMessageAt(channel, recordedAtByChannel[channel.id]),
],
);
}
static Channel _advanceLastMessageAt(Channel channel, int? createdAt) {
@@ -898,6 +763,10 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
}
void _handleLiveEvent(NostrEvent event) {
if (_applyUnreadDeletion(event)) {
state = state.whenData((channels) => List<Channel>.of(channels));
return;
}
final channelId = event.channelId;
if (channelId == null) return;
@@ -926,8 +795,8 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
authoredRootIds: _authoredRootIds,
mutedChannelIds: mutedChannelIds,
channelId: channel.id,
)) {
_recordUnreadEvent(channel, event, myPk);
) &&
_recordUnreadEvent(channel, event, myPk)) {
final eventTime = DateTime.fromMillisecondsSinceEpoch(
event.createdAt * 1000,
isUtc: true,

View File

@@ -110,7 +110,10 @@ extension _ChannelsNotifierLiveSubscriptions on ChannelsNotifier {
// events are already idempotent in the unread/timestamp stores.
if (!_lifecycleRef.mounted ||
_refreshCoordinator.currentScope() != fence.scope ||
!_desiredLiveChannelIds.contains(event.channelId)) {
!(_desiredLiveChannelIds.contains(event.channelId) ||
(event.kind == EventKind.deletion &&
event.channelId == null &&
chunk.any(_desiredLiveChannelIds.contains)))) {
return;
}
_handleLiveEvent(event);

View File

@@ -0,0 +1,150 @@
part of 'channels_provider_test.dart';
void _unreadDeletionCases() {
for (final format in [(5, true), (5, false), (9005, true)]) {
test(
'deleted mentions stop unread (kind ${format.$1}, h ${format.$2})',
() async {
NostrEvent message(String id, int at) => NostrEvent(
id: id,
pubkey: 'alice',
createdAt: at,
kind: 9,
tags: const [
['h', _channelA],
['p', 'me'],
],
content: 'hello',
sig: 'sig',
);
NostrEvent deletion(String id, String target, int at) => NostrEvent(
id: id,
pubkey: 'alice',
createdAt: at,
kind: format.$1,
tags: [
if (format.$2) ['h', _channelA],
['e', target],
],
content: '',
sig: 'sig',
);
final session = _FakeRelaySession(
memberships: [
_membership(_channelA, 'me'),
_membership(_channelB, 'me'),
],
metadata: [
_meta(id: _channelA, name: 'general'),
_meta(id: _channelB, name: 'other'),
],
enforceHistoryLimits: true,
deletionChannels: {
'missed-deletion': _channelA,
for (var i = 0; i < 600; i++) 'unreact-a-$i': _channelA,
for (var i = 0; i < 1000; i++) 'unreact-b-$i': _channelB,
},
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
await container.read(channelsProvider.future);
await _settle();
final mention = message('deleted-mention', 50);
session.emit(mention);
await _settle();
final notifier = container.read(channelsProvider.notifier);
expect(
notifier.observedUnreadEventsByChannel[_channelA],
contains(mention.id),
);
session.emit(deletion('delete', mention.id, 60));
await _settle();
expect(
notifier.observedUnreadEventsByChannel[_channelA] ?? {},
isEmpty,
);
expect(notifier.latestObservedByChannel, isNot(contains(_channelA)));
// A late history result must not restore the deleted message.
session.recentMessages = [mention];
await notifier.refresh();
await notifier.waitForUnreadCatchUp();
expect(
notifier.observedUnreadEventsByChannel[_channelA] ?? {},
isEmpty,
);
// Deletion can also arrive before its message.
session.emit(deletion('delete-before-message', 'late-mention', 70));
session.emit(message('late-mention', 65));
await _settle();
expect(
notifier.observedUnreadEventsByChannel[_channelA] ?? {},
isEmpty,
);
// Recover a deletion missed offline. The batch order must not matter.
final missed = message('offline-mention', 80);
session.emit(missed);
await _settle();
expect(
notifier.observedUnreadEventsByChannel[_channelA],
contains(missed.id),
);
session.recentMessages = [
missed,
deletion('missed-deletion', missed.id, 90),
];
await notifier.refresh();
await notifier.waitForUnreadCatchUp();
expect(
notifier.observedUnreadEventsByChannel[_channelA] ?? {},
isEmpty,
);
expect(notifier.latestObservedByChannel, isNot(contains(_channelA)));
// Reaction removals must neither consume the message window nor evict
// deletion evidence needed by this same multi-channel catch-up batch.
NostrEvent unreact(String id, int at) => NostrEvent(
id: id,
pubkey: 'alice',
createdAt: at,
kind: EventKind.deletion,
tags: [
['e', 'reaction-$id'],
],
content: '',
sig: 'sig',
);
session.recentMessages = [
missed,
deletion('missed-deletion', missed.id, 90),
for (var i = 0; i < 1000; i++) unreact('unreact-b-$i', 2000 + i),
];
await notifier.refresh();
await notifier.waitForUnreadCatchUp();
expect(
notifier.observedUnreadEventsByChannel[_channelA] ?? {},
isEmpty,
reason: 'this batch must retain all of its own deletion evidence',
);
session.recentMessages = [
missed,
deletion('missed-deletion', missed.id, 90),
for (var i = 0; i < 600; i++) message('kept-$i', 100 + i),
for (var i = 0; i < 600; i++) unreact('unreact-a-$i', 1000 + i),
for (var i = 0; i < 1000; i++) unreact('unreact-b-$i', 2000 + i),
];
await notifier.refresh();
await notifier.waitForUnreadCatchUp();
expect(
notifier.observedUnreadEventsByChannel[_channelA]?.keys,
unorderedEquals([for (var i = 0; i < 600; i++) 'kept-$i']),
reason:
'all surviving mentions remain unread, but deleted ones do not',
);
},
);
}
}

View File

@@ -14,6 +14,7 @@ import 'package:buzz/shared/read_state/read_state_provider.dart';
import 'package:buzz/shared/profile/user_cache_provider.dart';
part 'channels_provider_live_cases.dart';
part 'channels_provider_deletion_cases.dart';
part 'channels_provider_terminal_cases.dart';
part 'channels_provider_readiness_cases.dart';
part 'channels_provider_request_path_cases.dart';
@@ -32,6 +33,7 @@ part 'channels_provider_request_path_cases.dart';
/// events on demand.
void main() {
_unreadReadinessCases();
_unreadDeletionCases();
_requestPathCases();
const myPk = 'me';
@@ -2061,8 +2063,8 @@ void main() {
// Every HTTP chunk failed, so each batch also ran the websocket fallback.
expect(session.peakInFlight, {'latest': 4, 'unread': 4, 'huddle': 4});
// The fallback covered every channel of both batches.
expect(session.messageHistoryCount, 2 * ids.length);
// The fallback covered latest messages, unread messages, and deletions.
expect(session.messageHistoryCount, 3 * ids.length);
});
group('deadline-unavailable channel batches', () {
@@ -2188,36 +2190,54 @@ void main() {
// Quiet messages that fill the bounded catch-up window can hide an older
// unread event, so the full window still counts its oldest one, as plain
// backlog even when it mentions the reader.
for (final (count, expected) in [
(999, <String>[]),
(1000, ['quiet-0']),
for (final (count, deleted, expected) in [
(999, false, <String>[]),
(1000, false, ['quiet-0']),
(999, true, <String>[]),
(1000, true, ['quiet-1']),
]) {
test('$count quiet catch-up messages record $expected', () async {
final session = _FakeRelaySession(
memberships: [_membership(_channelA, myPk)],
metadata: [_meta(id: _channelA, name: 'general')],
recentMessages: [
for (var i = count - 1; i >= 0; i--)
message('quiet-$i', 100 + i, mention: true, quiet: true),
],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
await container.read(channelsProvider.future);
await _waitUntil(() => session.queryBatches.any(isUnread));
await _settle();
final notifier = container.read(channelsProvider.notifier);
expect(
notifier.observedUnreadEventsByChannel[_channelA]?.keys ?? const [],
expected,
);
for (final event
in notifier.observedUnreadEventsByChannel[_channelA]?.values ??
const <ObservedUnreadEvent>[]) {
expect(event.highPriority, isFalse);
expect(event.channelCatchUp, isTrue);
}
});
test(
'$count quiet messages, deletion $deleted, record $expected',
() async {
final session = _FakeRelaySession(
memberships: [_membership(_channelA, myPk)],
metadata: [_meta(id: _channelA, name: 'general')],
recentMessages: [
for (var i = count - 1; i >= 0; i--)
message('quiet-$i', 100 + i, mention: true, quiet: true),
if (deleted)
const NostrEvent(
id: 'quiet-deletion',
pubkey: 'alice',
createdAt: 2000,
kind: EventKind.deletion,
tags: [
['h', _channelA],
['e', 'quiet-0'],
],
content: '',
sig: 'sig',
),
],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
await container.read(channelsProvider.future);
await _waitUntil(() => session.queryBatches.any(isUnread));
await _settle();
final notifier = container.read(channelsProvider.notifier);
expect(
notifier.observedUnreadEventsByChannel[_channelA]?.keys ?? const [],
expected,
);
for (final event
in notifier.observedUnreadEventsByChannel[_channelA]?.values ??
const <ObservedUnreadEvent>[]) {
expect(event.highPriority, isFalse);
expect(event.channelCatchUp, isTrue);
}
},
);
}
// HTTP fails ordinarily, then a per-filter websocket fallback times out:
@@ -2309,7 +2329,18 @@ void main() {
.toSet(),
{_channelA, _channelB},
);
expect(session.queryBatches.last, hasLength(2));
expect(session.queryBatches.last, hasLength(4));
for (final channelId in [_channelA, _channelB]) {
expect(
session.queryBatches.last
.where((filter) => filter.tags['#h']!.single == channelId)
.map((filter) => filter.kinds),
[
EventKind.channelMessageEventKinds,
[EventKind.deletion, EventKind.nip29DeleteEvent],
],
);
}
expect(
session.queryBatches.last.every(
(filter) => filter.limit == 1000 && filter.since == 0,
@@ -2958,6 +2989,8 @@ class _FakeRelaySession extends RelaySessionNotifier {
this.hiddenDmEvents = const [],
this.huddleStarts = const [],
this.recentMessages = const [],
this.deletionChannels = const {},
this.enforceHistoryLimits = false,
this.membershipFailures = 0,
});
@@ -2973,6 +3006,8 @@ class _FakeRelaySession extends RelaySessionNotifier {
final List<NostrEvent> hiddenDmEvents;
final List<NostrEvent> huddleStarts;
List<NostrEvent> recentMessages;
final Map<String, String> deletionChannels;
final bool enforceHistoryLimits;
int membershipFailures;
int directoryFailures = 0;
bool failClaimedMemberMetadataQuery = false;
@@ -3378,13 +3413,21 @@ class _FakeRelaySession extends RelaySessionNotifier {
}
}
}
return messageSnapshot.where((event) {
return filters.any((filter) {
final matched = <String, NostrEvent>{};
for (final filter in filters) {
final matches = messageSnapshot.where((event) {
if (!filter.kinds.contains(event.kind)) return false;
for (final entry in filter.tags.entries) {
final tagName = entry.key.startsWith('#')
? entry.key.substring(1)
: entry.key;
// Relay #h matching uses stored channel metadata for h-less NIP-09.
if (tagName == 'h' &&
event.kind == EventKind.deletion &&
event.channelId == null &&
entry.value.contains(deletionChannels[event.id])) {
continue;
}
if (!event.tags.any(
(tag) =>
tag.length > 1 &&
@@ -3395,8 +3438,16 @@ class _FakeRelaySession extends RelaySessionNotifier {
}
}
return true;
});
}).toList();
}).toList();
if (enforceHistoryLimits) {
matches.sort((a, b) => b.createdAt.compareTo(a.createdAt));
}
for (final event
in enforceHistoryLimits ? matches.take(filter.limit) : matches) {
matched[event.id] = event;
}
}
return matched.values.toList();
}
@override