perf(mobile): stop re-scanning the unread backlog on channel list rebuilds (#9780)

## Summary

Scrolling the mobile channel list hitched repeatedly after the app had
been closed for a long time.

To decide which rows are bold and which get a dot, the channel list read
every unread message held in memory, for every channel, on every
rebuild. After a long absence the unread catch-up holds up to 1000
messages per channel, so each list update cost more than a frame.

This change makes a list rebuild independent of the backlog size:

- A channel's messages stop being read once its bold and dot state is
decided.
- Each channel's result is reused until its messages or the read state
change. A new message re-reads only its own channel; reordering or
filtering the list re-reads nothing.

Which rows end up bold or dotted is unchanged.

### Related issue

N/A. None found.

### Testing

Before (left) and after (right), same script on an iPhone 17 simulator:
200 channels each holding 1000 unread messages, a list update every 150
ms, and a scripted finger (the crosshair) dragging at a steady 420 px
per second.


https://github.com/user-attachments/assets/07b39b61-406f-4b4b-baca-69aa5be42db7

| | Before | After |
|---|---|---|
| Frames drawn in the 11-second drag | 279 | 499 |
| Frames over 25 ms | 127 (46%) | 92 (18%) |
| Median frame | 21.1 ms | 17.2 ms |
| Worst frame | 116.8 ms | 65.2 ms |

The recording uses scripted data in a debug build, which drops some
frames even with no list updates, so the "after" side is not perfectly
smooth.

Whole frame after one list update, 200 channels, in a widget test on a
Mac (not a phone):

| Unread messages held per channel | Before | After |
|---|---|---|
| 0 | 13.3 ms | 12.7 ms |
| 300 | 16.5 ms | 6.8 ms |
| 1000 | 37.4 ms | 6.6 ms |

- New tests in `channel_unread_test.dart` compare the new pass with a
copy of the old full scan across a table of cases and 600 random steps
of adds, deletions and read marks, and count messages read to guard the
early exit and the reuse without timing.
- `flutter analyze` and the mobile channel and home tests (2,983) passed
with these two commits on `8827f986e43`. They were not rerun after the
rebase onto current `main`, so CI is the check for that.
- Not run on a phone or against a real community.

Worth a close look in review: the reuse depends on every place that
changes the stored unread messages marking that channel as changed. The
new tests drive this through a stand-in, so they do not prove each real
call site does it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: mtoohey <mtoohey@squareup.com>
Signed-off-by: Matt Toohey <contact@matttoohey.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Matt Toohey
2026-11-20 18:01:03 +11:00
committed by GitHub
parent ee4a6ed6b6
commit a79cbb4664
9 changed files with 704 additions and 38 deletions

View File

@@ -687,7 +687,7 @@ extension _ObservedUnreadRecording on ChannelsNotifier {
!_isBroadcastReply(event);
final isHighPriority =
channel.isDm || (!countQuiet && isHighPriorityEvent(event.tags, myPk));
recordObservedUnreadEvent(
final inserted = recordObservedUnreadEvent(
_observedUnreadEventsByChannel,
channel.id,
makeObservedUnreadEvent(
@@ -702,6 +702,10 @@ extension _ObservedUnreadRecording on ChannelsNotifier {
_unreadCatchUpLimit,
);
// Refresh and reconnect replay history the registry already holds. Only
// an insertion changes the channel's events, so only it stamps them.
if (inserted) _observedUnreadRevisions.touch(channel.id);
final current = _latestObservedByChannel[channel.id] ?? 0;
if (event.createdAt > current) {
_latestObservedByChannel[channel.id] = event.createdAt;

View File

@@ -66,12 +66,14 @@ extension _ChannelThreadFollows on ChannelsNotifier {
for (final MapEntry(key: channelId, value: events)
in _observedUnreadEventsByChannel.entries) {
if (dmIds.contains(channelId)) continue;
final before = events.length;
events.removeWhere(
(_, event) =>
!event.highPriority &&
event.rootId != null &&
unfollowed.contains(event.rootId),
);
if (events.length != before) _observedUnreadRevisions.touch(channelId);
}
if (widened.isNotEmpty) {
// Only the widened threads' channels catch up again; a root whose

View File

@@ -57,43 +57,137 @@ _computeHighlights({
final latestObservedByChannel = channelsNotifier.latestObservedByChannel;
final observedEventsByChannel =
channelsNotifier.observedUnreadEventsByChannel;
// Lists rebuild far more often than unread evidence changes, and a backlog
// can hold a thousand events per channel: reuse each channel's outcome
// until its events or the read state change.
final revisionOf = observedEventsByChannel is ObservedUnreadSnapshot
? observedEventsByChannel.revisionOf
: null;
final memo = revisionOf == null
? null
: (_memos[channelsNotifier] ??= _HighlightMemo()).entriesFor(
readState,
separateAttention: separateAttention,
);
for (final channel in channels) {
if (forcedChannelIds.contains(channel.id)) {
unread.add(channel.id);
if (separateAttention) rowUnread.add(channel.id);
}
final latestObserved = latestObservedByChannel[channel.id];
if (latestObserved == null) continue;
final channelReadAt = readState.effectiveTimestamp(channel.id);
if (channelReadAt != null && latestObserved <= channelReadAt) continue;
final observedEvents = observedEventsByChannel[channel.id];
if (observedEvents == null) continue;
final seenAt = separateAttention
? readState.contexts['seen:${channel.id}']
: null;
for (final event in observedEvents.values) {
final readAt = observedUnreadEventReadAt(
event,
channel.id,
readState.effectiveTimestamp,
final revision = revisionOf?.call(channel.id);
final cached = memo?[channel.id];
final int flags;
if (cached != null &&
cached.revision == revision &&
cached.latestObserved == latestObserved &&
cached.isDm == channel.isDm) {
flags = cached.flags;
} else {
flags = _channelHighlights(
channel: channel,
readState: readState,
forced: forcedChannelIds.contains(channel.id),
latestObserved: latestObserved,
observedEvents: observedEventsByChannel[channel.id],
separateAttention: separateAttention,
);
if (readAt != null && event.createdAt <= readAt) continue;
if (!separateAttention || channel.isDm || event.channelCatchUp) {
unread.add(channel.id);
if (separateAttention &&
(channel.isDm || seenAt == null || event.createdAt > seenAt)) {
rowUnread.add(channel.id);
}
}
if (separateAttention && (channel.isDm || !event.channelCatchUp)) {
attention.add(channel.id);
if (memo != null && revision != null) {
memo[channel.id] = (
revision: revision,
latestObserved: latestObserved,
isDm: channel.isDm,
flags: flags,
);
}
}
if (flags & _unread != 0) unread.add(channel.id);
if (flags & _rowUnread != 0) rowUnread.add(channel.id);
if (flags & _attention != 0) attention.add(channel.id);
}
return highlights;
}
const _unread = 1;
const _rowUnread = 2;
const _attention = 4;
/// One channel's highlight flags. Stops reading events once no later event
/// could change the outcome.
int _channelHighlights({
required Channel channel,
required ReadStateState readState,
required bool forced,
required int? latestObserved,
required Map<String, ObservedUnreadEvent>? observedEvents,
required bool separateAttention,
}) {
var flags = 0;
if (forced) {
flags |= _unread;
if (separateAttention) flags |= _rowUnread;
}
// Every flag an event could still set. Without separate attention only
// `unread` exists; a DM's first unread event sets all three at once.
final decided = separateAttention
? _unread | _rowUnread | _attention
: _unread;
if (flags == decided) return flags;
if (latestObserved == null) return flags;
final channelReadAt = readState.effectiveTimestamp(channel.id);
if (channelReadAt != null && latestObserved <= channelReadAt) return flags;
if (observedEvents == null) return flags;
final seenAt = separateAttention
? readState.contexts['seen:${channel.id}']
: null;
for (final event in observedEvents.values) {
final readAt = observedUnreadEventReadAt(
event,
channel.id,
readState.effectiveTimestamp,
);
if (readAt != null && event.createdAt <= readAt) continue;
if (!separateAttention || channel.isDm || event.channelCatchUp) {
flags |= _unread;
if (separateAttention &&
(channel.isDm || seenAt == null || event.createdAt > seenAt)) {
flags |= _rowUnread;
}
}
if (separateAttention && (channel.isDm || !event.channelCatchUp)) {
flags |= _attention;
}
if (flags == decided) break;
}
return flags;
}
typedef _MemoEntry = ({
int revision,
int? latestObserved,
bool isDm,
int flags,
});
/// Per-notifier memo, so it ends with the notifier's community and identity.
final _memos = Expando<_HighlightMemo>();
/// Channel outcomes for one read state, per `separateAttention` mode. Read
/// state is immutable and replaced on every change, so identity is the key.
class _HighlightMemo {
ReadStateState? _readState;
final _combined = <String, _MemoEntry>{};
final _separate = <String, _MemoEntry>{};
Map<String, _MemoEntry> entriesFor(
ReadStateState readState, {
required bool separateAttention,
}) {
if (!identical(_readState, readState)) {
_readState = readState;
_combined.clear();
_separate.clear();
}
return separateAttention ? _separate : _combined;
}
}

View File

@@ -35,7 +35,10 @@ extension _UnreadDeletions on ChannelsNotifier {
// The deleted event may have been the marker standing in for a full
// window of quiet messages, which can hide older unread ones. Read the
// channel's whole window again rather than only since the last read.
if (observed?.length != before) _unreadCaughtUpByChannel.remove(id);
if (observed?.length != before) {
_unreadCaughtUpByChannel.remove(id);
_observedUnreadRevisions.touch(id);
}
if (observed == null || observed.isEmpty) {
_observedUnreadEventsByChannel.remove(id);
_latestObservedByChannel.remove(id);

View File

@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:math';
@@ -117,6 +118,8 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
_unreadCaughtUpByChannel = {};
final Map<String, Map<String, ObservedUnreadEvent>>
_observedUnreadEventsByChannel = {};
// Touched wherever the two maps above change; highlights memoize on it.
final _observedUnreadRevisions = ObservedUnreadRevisions();
final Map<String, Set<String>> _unreadDeletedIdsByChannel = {};
final Set<String> _unscopedUnreadDeletedIds = {};
Set<String> _participatedRootIds = {};
@@ -214,11 +217,10 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
}
Map<String, Map<String, ObservedUnreadEvent>>
get observedUnreadEventsByChannel =>
Map<String, Map<String, ObservedUnreadEvent>>.unmodifiable({
for (final entry in _observedUnreadEventsByChannel.entries)
entry.key: Map<String, ObservedUnreadEvent>.unmodifiable(entry.value),
});
get observedUnreadEventsByChannel => ObservedUnreadSnapshot({
for (final entry in _observedUnreadEventsByChannel.entries)
entry.key: UnmodifiableMapView(entry.value),
}, _observedUnreadRevisions.of);
@override
Future<List<Channel>> build() async {
@@ -331,6 +333,7 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
_latestObservedByChannel.clear();
_activityRevisions.clear();
_observedUnreadEventsByChannel.clear();
_observedUnreadRevisions.touchAll();
_unreadCaughtUpByChannel.clear();
_unreadDeletedIdsByChannel.clear();
_unscopedUnreadDeletedIds.clear();
@@ -993,7 +996,9 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
void clearObservedUnreadForChannel(String channelId) {
_latestObservedByChannel.remove(channelId);
_activityRevisions.remove(channelId);
_observedUnreadEventsByChannel.remove(channelId);
if (_observedUnreadEventsByChannel.remove(channelId) != null) {
_observedUnreadRevisions.touch(channelId);
}
state = state.whenData((channels) => List<Channel>.of(channels));
}

View File

@@ -1,3 +1,5 @@
import 'dart:collection';
import '../../../shared/read_state/read_state_format.dart';
import '../../../shared/relay/nostr_models.dart';
@@ -28,6 +30,36 @@ class ObservedUnreadEvent {
});
}
/// Per-channel change stamps for the observed unread registry. Every add,
/// eviction, deletion or clear of a channel's events must [touch] it, so
/// readers can reuse work derived from an unchanged channel.
class ObservedUnreadRevisions {
int _next = 0;
int _floor = 0;
final Map<String, int> _byChannel = {};
/// Changes whenever [channelId]'s observed events may have changed.
int of(String channelId) => _byChannel[channelId] ?? _floor;
void touch(String channelId) => _byChannel[channelId] = ++_next;
void touchAll() {
_byChannel.clear();
_floor = ++_next;
}
}
/// Observed unread events by channel, with the stamp that says when a
/// channel's events last changed. Only a view carrying stamps may be
/// memoized against; a plain map is always read in full.
class ObservedUnreadSnapshot
extends UnmodifiableMapView<String, Map<String, ObservedUnreadEvent>> {
ObservedUnreadSnapshot(super.map, this.revisionOf);
/// See [ObservedUnreadRevisions.of].
final int Function(String channelId) revisionOf;
}
ObservedUnreadEvent makeObservedUnreadEvent({
required String id,
required int createdAt,

View File

@@ -1,7 +1,11 @@
import 'dart:collection';
import 'dart:math';
import 'package:buzz/features/channels/channel.dart';
import 'package:buzz/features/channels/channel_unread.dart';
import 'package:buzz/features/channels/channels_provider.dart';
import 'package:buzz/features/channels/unread_badge/observed_unread_event.dart';
import 'package:buzz/shared/read_state/read_state_format.dart';
import 'package:buzz/shared/read_state/read_state_provider.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -48,6 +52,173 @@ class _Channels extends ChannelsNotifier {
};
}
typedef _Highlights = ({
Set<String> unread,
Set<String> rowUnread,
Set<String> attention,
});
ObservedUnreadEvent _eventAt(
String id,
int createdAt, {
String type = 'stream',
String? root,
bool mention = false,
}) => makeObservedUnreadEvent(
id: id,
createdAt: createdAt,
rootId: root,
highPriority: mention,
channelType: type,
isThreadedReply: root != null,
);
/// The registry as the real notifier exposes it: a stamped snapshot, so
/// highlights may be reused. Counts every event a pass reads.
class _StampedChannels extends ChannelsNotifier {
final Map<String, Map<String, ObservedUnreadEvent>> events = {};
final revisions = ObservedUnreadRevisions();
int visits = 0;
void add(String channelId, ObservedUnreadEvent event) {
(events[channelId] ??= {})[event.id] = event;
revisions.touch(channelId);
}
void remove(String channelId, String eventId) {
events[channelId]?.remove(eventId);
if (events[channelId]?.isEmpty ?? false) events.remove(channelId);
revisions.touch(channelId);
}
@override
Map<String, int> get latestObservedByChannel => {
for (final MapEntry(:key, :value) in events.entries)
key: value.values.map((event) => event.createdAt).reduce(max),
};
@override
Map<String, Map<String, ObservedUnreadEvent>>
get observedUnreadEventsByChannel => ObservedUnreadSnapshot({
for (final MapEntry(:key, :value) in events.entries)
key: _CountingMap(value, () => visits++),
}, revisions.of);
}
class _CountingMap extends MapView<String, ObservedUnreadEvent> {
_CountingMap(super.map, this.onVisit);
final void Function() onVisit;
@override
Iterable<ObservedUnreadEvent> get values => super.values.map((event) {
onVisit();
return event;
});
}
/// The full-scan pass the memoized, early-exiting one must keep matching.
_Highlights _fullScan({
required Iterable<Channel> channels,
required ReadStateState readState,
required Map<String, Map<String, ObservedUnreadEvent>> events,
required bool separateAttention,
}) {
final unread = <String>{};
final rowUnread = <String>{};
final attention = <String>{};
final highlights = (
unread: unread,
rowUnread: rowUnread,
attention: attention,
);
if (!readState.isReady) return highlights;
final forced = readState.locallyForcedChannelIds;
for (final channel in channels) {
if (forced.contains(channel.id)) {
unread.add(channel.id);
if (separateAttention) rowUnread.add(channel.id);
}
final observed = events[channel.id];
if (observed == null) continue;
final latest = observed.values.map((event) => event.createdAt).reduce(max);
final channelReadAt = readState.effectiveTimestamp(channel.id);
if (channelReadAt != null && latest <= channelReadAt) continue;
final seenAt = separateAttention
? readState.contexts['seen:${channel.id}']
: null;
for (final event in observed.values) {
final readAt = observedUnreadEventReadAt(
event,
channel.id,
readState.effectiveTimestamp,
);
if (readAt != null && event.createdAt <= readAt) continue;
if (!separateAttention || channel.isDm || event.channelCatchUp) {
unread.add(channel.id);
if (separateAttention &&
(channel.isDm || seenAt == null || event.createdAt > seenAt)) {
rowUnread.add(channel.id);
}
}
if (separateAttention && (channel.isDm || !event.channelCatchUp)) {
attention.add(channel.id);
}
}
}
return highlights;
}
void _expectMatchesFullScan(
_StampedChannels notifier,
List<Channel> channels,
ReadStateState readState, {
String? reason,
}) {
final expected = _fullScan(
channels: channels,
readState: readState,
events: notifier.events,
separateAttention: true,
);
// Twice: a pass that reuses its previous outcome must agree with itself.
for (var pass = 0; pass < 2; pass++) {
final actual = computeChannelListHighlights(
channels: channels,
readState: readState,
channelsNotifier: notifier,
);
expect(actual.unread, expected.unread, reason: reason);
expect(actual.rowUnread, expected.rowUnread, reason: reason);
expect(actual.attention, expected.attention, reason: reason);
expect(
computeUnreadChannelIds(
channels: channels,
readState: readState,
channelsNotifier: notifier,
),
_fullScan(
channels: channels,
readState: readState,
events: notifier.events,
separateAttention: false,
).unread,
reason: reason,
);
}
}
ReadStateState _reads(
Map<String, int> contexts, {
bool isReady = true,
Set<String> forced = const {},
}) => ReadStateState(
isReady: isReady,
pubkey: 'pk',
contexts: contexts,
version: 0,
forcedUnreadContexts: {for (final id in forced) id: id},
);
void main() {
final channels = [
_channel('backlog'),
@@ -128,4 +299,226 @@ void main() {
expect(highlights.unread, isEmpty);
expect(highlights.attention, isEmpty);
});
group('memoized, early-exiting pass', () {
final listed = [
_channel('stream'),
_channel('dm', type: 'dm'),
_channel('quiet'),
];
_StampedChannels seeded() => _StampedChannels()
..add('stream', _eventAt('m1', 10))
..add('stream', _eventAt('r1', 12, root: 'root'))
..add('stream', _eventAt('p1', 14, mention: true))
..add('stream', _eventAt('m2', 16))
..add('dm', _eventAt('d1', 10, type: 'dm'))
..add('dm', _eventAt('d2', 16, type: 'dm', root: 'dm-root'));
final cases = <String, ReadStateState>{
'nothing read': _reads({}),
'read state not ready': _reads({}, isReady: false),
'channel marker covers everything': _reads({'stream': 16, 'dm': 16}),
'channel marker covers part': _reads({'stream': 13, 'dm': 12}),
'catch-up read, attention left': _reads({
activityContextKey('stream'): 16,
}),
'attention read, catch-up left': _reads({
threadContextKey('root'): 12,
msgContextKey('p1'): 14,
}),
'thread activity mark reads the reply': _reads({
threadActivityContextKey('root'): 12,
}),
'every event read by its own mark': _reads({
msgContextKey('m1'): 10,
msgContextKey('r1'): 12,
msgContextKey('p1'): 14,
msgContextKey('m2'): 16,
msgContextKey('d1'): 10,
msgContextKey('d2'): 16,
}),
'seen mark covers the backlog': _reads({
'seen:stream': 16,
'seen:dm': 16,
}),
'seen mark covers part of the backlog': _reads({'seen:stream': 11}),
'forced with evidence': _reads({}, forced: {'stream', 'dm'}),
'forced over a read channel': _reads(
{'stream': 16, 'dm': 16},
forced: {'stream', 'dm'},
),
'forced with nothing observed': _reads({}, forced: {'quiet'}),
'forced, attention read': _reads(
{threadContextKey('root'): 12, msgContextKey('p1'): 14},
forced: {'stream'},
),
};
for (final MapEntry(key: name, value: readState) in cases.entries) {
test('matches the full scan: $name', () {
_expectMatchesFullScan(seeded(), listed, readState);
});
}
test('matches the full scan as events, reads and channels change', () {
final random = Random(7);
final all = [
for (var i = 0; i < 6; i++)
_channel('c$i', type: i.isEven ? 'stream' : 'dm'),
];
final notifier = _StampedChannels();
var contexts = <String, int>{};
var forced = <String>{};
var readState = _reads(contexts);
var listed = all;
for (var step = 0; step < 600; step++) {
final channel = all[random.nextInt(all.length)];
final at = 1 + random.nextInt(30);
switch (random.nextInt(8)) {
case 0 || 1 || 2:
final kind = random.nextInt(3);
notifier.add(
channel.id,
_eventAt(
'e$step',
at,
type: channel.channelType,
root: kind == 1 ? 'root${random.nextInt(3)}' : null,
mention: kind == 2,
),
);
case 3:
final ids = notifier.events[channel.id]?.keys.toList() ?? [];
if (ids.isNotEmpty) {
notifier.remove(channel.id, ids[random.nextInt(ids.length)]);
}
case 4:
final ids = notifier.events[channel.id]?.keys.toList() ?? [];
final key = [
channel.id,
'seen:${channel.id}',
activityContextKey(channel.id),
threadContextKey('root${random.nextInt(3)}'),
threadActivityContextKey('root${random.nextInt(3)}'),
if (ids.isNotEmpty)
msgContextKey(ids[random.nextInt(ids.length)]),
];
contexts = {...contexts, key[random.nextInt(key.length)]: at};
readState = _reads(contexts, forced: forced);
case 5:
forced = forced.contains(channel.id)
? forced.difference({channel.id})
: {...forced, channel.id};
readState = _reads(contexts, forced: forced);
case 6:
listed = [
for (final candidate in all)
if (random.nextBool()) candidate,
];
case 7:
readState = _reads(
contexts,
forced: forced,
isReady: random.nextInt(4) != 0,
);
}
_expectMatchesFullScan(
notifier,
listed,
readState,
reason: 'step $step',
);
}
});
test('a channel type change is not served from the old outcome', () {
final notifier = _StampedChannels()..add('c', _eventAt('m', 10));
final readState = _reads({});
_expectMatchesFullScan(notifier, [_channel('c')], readState);
_expectMatchesFullScan(notifier, [_channel('c', type: 'dm')], readState);
});
test('a rebuild reads no events until its inputs change', () {
const backlog = 1000;
final listed = [for (var i = 0; i < 20; i++) _channel('c$i')];
final notifier = _StampedChannels();
for (final channel in listed) {
for (var i = 0; i < backlog; i++) {
notifier.add(channel.id, _eventAt('${channel.id}-$i', 10 + i));
}
}
var readState = _reads({});
int pass() {
notifier.visits = 0;
final highlights = computeChannelListHighlights(
channels: listed,
readState: readState,
channelsNotifier: notifier,
);
expect(highlights.rowUnread, {for (final c in listed) c.id});
return notifier.visits;
}
// Backlog alone never decides attention, so the first pass reads it all.
expect(pass(), listed.length * backlog);
expect(pass(), 0, reason: 'unchanged inputs');
expect(pass(), 0, reason: 'unchanged inputs, again');
// The list order and membership are not part of a channel's outcome.
listed.insert(0, listed.removeLast());
expect(pass(), 0, reason: 'reordered list');
notifier.add('c3', _eventAt('late', 5000));
expect(pass(), backlog + 1, reason: 'only the changed channel');
notifier.remove('c3', 'late');
expect(pass(), backlog, reason: 'a deletion invalidates its channel');
readState = _reads({'c0': 10});
expect(pass(), listed.length * backlog, reason: 'new read state');
expect(pass(), 0);
});
test('a channel stops being read once its outcome is decided', () {
const backlog = 1000;
final notifier = _StampedChannels();
for (final id in ['stream', 'forced']) {
notifier
..add(id, _eventAt('$id-m', 10))
..add(id, _eventAt('$id-p', 11, mention: true));
}
notifier.add('dm', _eventAt('dm-0', 10, type: 'dm'));
for (final id in ['stream', 'forced', 'dm']) {
for (var i = 0; i < backlog; i++) {
notifier.add(
id,
_eventAt('$id-b$i', 20 + i, type: id == 'dm' ? 'dm' : 'stream'),
);
}
}
final listed = [
_channel('stream'),
_channel('forced'),
_channel('dm', type: 'dm'),
];
final readState = _reads({}, forced: {'forced'});
final highlights = computeChannelListHighlights(
channels: listed,
readState: readState,
channelsNotifier: notifier,
);
expect(highlights.attention, {'stream', 'forced', 'dm'});
// Backlog then mention decides a stream; a DM's first event decides it.
expect(notifier.visits, 2 + 2 + 1);
notifier.visits = 0;
computeUnreadChannelIds(
channels: listed,
readState: readState,
channelsNotifier: notifier,
);
// One unread event bolds; a forced channel needs none.
expect(notifier.visits, 1 + 0 + 1);
});
});
}

View File

@@ -21,6 +21,7 @@ import 'package:buzz/shared/channels/open_channel_directory_storage.dart';
import 'package:buzz/features/channels/channel_management_provider.dart';
import 'package:buzz/features/channels/channel_mutes/channel_mutes_provider.dart';
import 'package:buzz/features/channels/channel_mutes/channel_mutes_storage.dart';
import 'package:buzz/features/channels/channel_unread.dart';
import 'package:buzz/features/channels/channels_provider.dart';
import 'package:buzz/features/channels/thread_follows/thread_follows_provider.dart';
import 'package:buzz/features/channels/unread_badge/observed_unread_event.dart';
@@ -43,6 +44,7 @@ part 'channels_provider_join_cases.dart';
part 'channels_provider_follow_cases.dart';
part 'channels_provider_saved_directory_cases.dart';
part 'channels_provider_thread_interest_cases.dart';
part 'channels_provider_unread_revision_cases.dart';
/// Tests for [ChannelsNotifier] in the pure-Nostr world.
///
@@ -60,6 +62,7 @@ void main() {
_huddleNavigationCases();
_unreadReadinessCases();
_unreadDeletionCases();
_unreadRevisionCases();
_requestPathCases();
_threadActivityCases();
_confirmedJoinCases();

View File

@@ -0,0 +1,130 @@
part of 'channels_provider_test.dart';
/// Read state that counts marker lookups. A highlight pass looks markers up
/// only while it reads a channel's events, so a pass served from the memo
/// makes none.
class _CountingReadState extends ReadStateState {
_CountingReadState()
: super(isReady: true, pubkey: 'me', contexts: const {}, version: 0);
int lookups = 0;
@override
int? effectiveTimestamp(String contextId) {
lookups++;
return super.effectiveTimestamp(contextId);
}
}
void _unreadRevisionCases() {
test('replayed history and no-op changes keep cached highlights', () async {
final base = DateTime.now().millisecondsSinceEpoch ~/ 1000 - 100;
final root = 'f' * 64;
NostrEvent mention(String id, int at) => NostrEvent(
id: id,
pubkey: 'alice',
createdAt: base + at,
kind: 9,
tags: const [
['h', _channelA],
['p', 'me'],
],
content: 'hello',
sig: 'sig',
);
final reply = NostrEvent(
id: 'followed-reply',
pubkey: 'alice',
createdAt: base + 55,
kind: 9,
tags: [
['h', _channelA],
['e', root, '', 'root'],
['e', root, '', 'reply'],
],
content: 'reply',
sig: 'sig',
);
final session = _FakeRelaySession(
memberships: [_membership(_channelA, 'me'), _membership(_channelB, 'me')],
metadata: [
_meta(id: _channelA, name: 'general'),
_meta(id: _channelB, name: 'other'),
],
);
final follows = _TestFollows();
final container = _buildContainer(session: session, follows: follows);
addTearDown(container.dispose);
final listed = await container.read(channelsProvider.future);
await _settle();
final notifier = container.read(channelsProvider.notifier);
follows.choose(followed: {root});
final first = mention('first-mention', 50);
session.emit(first);
session.emit(reply);
await _settle();
final readState = _CountingReadState();
int revision([String channelId = _channelA]) =>
(notifier.observedUnreadEventsByChannel as ObservedUnreadSnapshot)
.revisionOf(channelId);
int pass() {
readState.lookups = 0;
final highlights = computeChannelListHighlights(
channels: listed,
readState: readState,
channelsNotifier: notifier,
);
expect(highlights.attention, {_channelA});
return readState.lookups;
}
expect(pass(), greaterThan(0), reason: 'the first pass reads the events');
expect(pass(), 0, reason: 'unchanged inputs');
final held = revision();
final heldEmpty = revision(_channelB);
Set<String> ids() =>
notifier.observedUnreadEventsByChannel[_channelA]!.keys.toSet();
expect(ids(), {first.id, reply.id});
// Refresh fetches history the registry already holds.
session.recentMessages = [first, reply];
await notifier.refresh();
await notifier.waitForUnreadCatchUp();
expect(ids(), {first.id, reply.id});
expect(revision(), held, reason: 'replayed catch-up');
expect(pass(), 0, reason: 'replayed catch-up');
// So does a live redelivery after reconnect.
session.emit(first);
await _settle();
expect(revision(), held, reason: 'replayed live event');
expect(pass(), 0, reason: 'replayed live event');
// An unfollow that removes no held reply, and a clear of a channel that
// holds nothing, change no events either.
follows.choose(followed: {root}, unfollowed: {'e' * 64});
await _settle();
notifier.clearObservedUnreadForChannel(_channelB);
expect(revision(), held, reason: 'unfollow with nothing to drop');
expect(revision(_channelB), heldEmpty, reason: 'clearing an empty channel');
expect(pass(), 0, reason: 'no-op unfollow and clear');
// Each real change still invalidates the channel.
session.emit(mention('second-mention', 60));
await _settle();
final afterInsert = revision();
expect(afterInsert, greaterThan(held), reason: 'a new event');
expect(pass(), greaterThan(0), reason: 'a new event');
follows.choose(unfollowed: {root});
await _settle();
expect(ids(), isNot(contains(reply.id)));
final afterUnfollow = revision();
expect(afterUnfollow, greaterThan(afterInsert), reason: 'a dropped reply');
expect(pass(), greaterThan(0), reason: 'a dropped reply');
notifier.clearObservedUnreadForChannel(_channelA);
expect(revision(), greaterThan(afterUnfollow), reason: 'a real clear');
});
}