Skip to content

Commit 72bb6cf

Browse files
npub12zsjdqx8dud99s9h47xmk9lq93vryf7zjrae8wdrmma52cg5yglseyulstklopez4212
andcommitted
fix(mobile): order live thread summary snapshots
Buffer live thread summaries that race initial window hydration, retain the newest page-or-live snapshot by relay timestamp, and ignore delayed recounts that would restore stale reply badges. Co-authored-by: klopez4212 <[email protected]> Signed-off-by: klopez4212 <[email protected]>
1 parent b454f3f commit 72bb6cf

4 files changed

Lines changed: 177 additions & 43 deletions

File tree

‎mobile/lib/features/channels/channel_messages_provider.dart‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,19 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
173173
);
174174

175175
void _handleLiveEvent(NostrEvent event, {bool authoritative = true}) {
176+
// A live summary can race the initial channel-window query. Buffer it in
177+
// the window store even before that query installs its first page, rather
178+
// than treating metadata as an ordinary websocket timeline event.
179+
if (event.kind == EventKind.channelThreadSummary && !_usingChannelWindow) {
180+
if (_mergeWindowEventIntoStore(event) && !_initInFlight) {
181+
final current =
182+
state.value ?? _lastKnownMessages ?? const <NostrEvent>[];
183+
_lastKnownMessages = current;
184+
state = AsyncData(current);
185+
}
186+
return;
187+
}
188+
176189
// Reply ownership and its thread-local overlay must transition together.
177190
// The authoritative thread query performs both confirmations after it
178191
// contains the reply; a live echo only triggers that query below.

‎mobile/lib/features/channels/channel_window.dart‎

Lines changed: 63 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,40 @@ class ChannelWindowThreadSummary {
2323
});
2424
}
2525

26+
/// A thread-summary snapshot received from the live channel subscription.
27+
///
28+
/// [createdAt] is the relay event timestamp used to reject delayed snapshots
29+
/// after a fresher recount has already been displayed.
30+
class ChannelWindowLiveThreadSummary {
31+
final ChannelWindowThreadSummary summary;
32+
final int createdAt;
33+
34+
const ChannelWindowLiveThreadSummary({
35+
required this.summary,
36+
required this.createdAt,
37+
});
38+
}
39+
2640
class ChannelWindowRow {
2741
final NostrEvent event;
2842
final ChannelWindowThreadSummary? thread;
43+
final int? threadSummaryCreatedAt;
2944

30-
const ChannelWindowRow({required this.event, this.thread});
45+
const ChannelWindowRow({
46+
required this.event,
47+
this.thread,
48+
this.threadSummaryCreatedAt,
49+
});
3150

32-
ChannelWindowRow copyWith({ChannelWindowThreadSummary? thread}) =>
33-
ChannelWindowRow(event: event, thread: thread ?? this.thread);
51+
ChannelWindowRow copyWith({
52+
ChannelWindowThreadSummary? thread,
53+
int? threadSummaryCreatedAt,
54+
}) => ChannelWindowRow(
55+
event: event,
56+
thread: thread ?? this.thread,
57+
threadSummaryCreatedAt:
58+
threadSummaryCreatedAt ?? this.threadSummaryCreatedAt,
59+
);
3460
}
3561

3662
class ChannelWindowPage {
@@ -59,7 +85,7 @@ class ChannelWindowStore {
5985
/// Kept beside the pages rather than folded into [ChannelWindowRow.thread]
6086
/// because a root can be in [liveOverlay] instead — a message you just sent
6187
/// has no row yet, and its reply count has to land somewhere.
62-
final Map<String, ChannelWindowThreadSummary> liveThreadSummaries;
88+
final Map<String, ChannelWindowLiveThreadSummary> liveThreadSummaries;
6389

6490
const ChannelWindowStore({
6591
required this.pages,
@@ -96,6 +122,7 @@ ChannelWindowPage parseChannelWindowResponse(
96122
if (rowIndex == null) continue;
97123
rows[rowIndex] = rows[rowIndex].copyWith(
98124
thread: parseChannelWindowThreadSummary(event),
125+
threadSummaryCreatedAt: event.createdAt,
99126
);
100127
}
101128

@@ -150,13 +177,28 @@ ChannelWindowStore replaceNewestChannelWindow(
150177
liveAux: current.liveAux
151178
.where((event) => !auxIds.contains(event.id))
152179
.toList(),
153-
// A refetched row carries its own summary and is authoritative, so drop the
154-
// live entry for it. Roots still only in the overlay keep theirs.
155-
liveThreadSummaries: _retainLiveSummaries(current, rowIds),
180+
// A page summary supersedes an equal-or-older live recount. A fresher live
181+
// recount can race the query response, so retain that one on top.
182+
liveThreadSummaries: _retainLiveSummariesAfterPage(current, page.rows),
156183
);
157184
}
158185

159-
Map<String, ChannelWindowThreadSummary> _retainLiveSummaries(
186+
Map<String, ChannelWindowLiveThreadSummary> _retainLiveSummariesAfterPage(
187+
ChannelWindowStore current,
188+
List<ChannelWindowRow> rows,
189+
) {
190+
final rowsById = {for (final row in rows) row.event.id: row};
191+
return {
192+
for (final entry in current.liveThreadSummaries.entries)
193+
if (rowsById[entry.key] == null ||
194+
rowsById[entry.key]!.thread == null ||
195+
entry.value.createdAt >
196+
(rowsById[entry.key]!.threadSummaryCreatedAt ?? -1))
197+
entry.key: entry.value,
198+
};
199+
}
200+
201+
Map<String, ChannelWindowLiveThreadSummary> _retainLiveSummaries(
160202
ChannelWindowStore current,
161203
Set<String> supersededRootIds,
162204
) {
@@ -236,11 +278,21 @@ ChannelWindowStore mergeLiveChannelWindowEvent(
236278
} catch (_) {
237279
return current;
238280
}
281+
final existing = current.liveThreadSummaries[rootId];
282+
if (existing != null && existing.createdAt >= event.createdAt) {
283+
return current;
284+
}
239285
return ChannelWindowStore(
240286
pages: current.pages,
241287
liveOverlay: current.liveOverlay,
242288
liveAux: current.liveAux,
243-
liveThreadSummaries: {...current.liveThreadSummaries, rootId: summary},
289+
liveThreadSummaries: {
290+
...current.liveThreadSummaries,
291+
rootId: ChannelWindowLiveThreadSummary(
292+
summary: summary,
293+
createdAt: event.createdAt,
294+
),
295+
},
244296
);
245297
}
246298

@@ -316,7 +368,8 @@ Map<String, ChannelWindowThreadSummary> channelWindowThreadSummaries(
316368
for (final row in page.rows)
317369
if (row.thread != null) row.event.id: row.thread!,
318370
// Live entries last: they are the newer snapshot for any root they cover.
319-
...store.liveThreadSummaries,
371+
for (final entry in store.liveThreadSummaries.entries)
372+
entry.key: entry.value.summary,
320373
};
321374
}
322375

‎mobile/test/features/channels/channel_messages_provider_test.dart‎

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,47 @@ void main() {
5959
},
6060
);
6161

62+
test(
63+
'buffers a live thread summary until the initial window is installed',
64+
() async {
65+
final window = Completer<List<NostrEvent>>();
66+
final relaySession = _RecordingRelaySessionNotifier(
67+
queryResults: [window.future],
68+
);
69+
final container = _buildContainer(relaySession);
70+
addTearDown(container.dispose);
71+
72+
container.read(channelMessagesProvider(_channelId));
73+
await relaySession.subscribed;
74+
final notifier = container.read(
75+
channelMessagesProvider(_channelId).notifier,
76+
);
77+
78+
relaySession.emit(_summary(rootId: 'root', replyCount: 2));
79+
await _pumpEventQueue();
80+
expect(
81+
container.read(channelMessagesProvider(_channelId)).isLoading,
82+
isTrue,
83+
);
84+
85+
window.complete([
86+
_event(id: 'root', createdAt: 10),
87+
_summary(rootId: 'root', replyCount: 1, createdAt: 10),
88+
_bounds(),
89+
]);
90+
await _pumpEventQueue();
91+
92+
expect(notifier.threadSummaries['root']?.replyCount, 2);
93+
expect(
94+
container
95+
.read(channelMessagesProvider(_channelId))
96+
.value
97+
?.map((event) => event.id),
98+
['root'],
99+
);
100+
},
101+
);
102+
62103
test('still loads history when live subscription fails', () async {
63104
final relaySession = _RecordingRelaySessionNotifier(failSubscribe: true);
64105
final container = _buildContainer(relaySession);
@@ -598,11 +639,15 @@ NostrEvent _event({
598639
);
599640
}
600641

601-
NostrEvent _summary({required String rootId, required int replyCount}) {
642+
NostrEvent _summary({
643+
required String rootId,
644+
required int replyCount,
645+
int createdAt = 20,
646+
}) {
602647
return NostrEvent(
603-
id: 'summary-$rootId-$replyCount',
648+
id: 'summary-$rootId-$createdAt-$replyCount',
604649
pubkey: 'relay',
605-
createdAt: 20,
650+
createdAt: createdAt,
606651
kind: EventKind.channelThreadSummary,
607652
tags: [
608653
['h', _channelId],
@@ -685,6 +730,7 @@ class _RecordingRelaySessionNotifier extends RelaySessionNotifier {
685730
if (_queryResults.isEmpty) throw Exception('unsupported');
686731
final result = _queryResults.removeFirst();
687732
if (result is Exception) throw result;
733+
if (result is Future<List<NostrEvent>>) return await result;
688734
return (result as List<NostrEvent>).toList();
689735
}
690736

‎mobile/test/features/channels/channel_window_test.dart‎

Lines changed: 52 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -188,18 +188,49 @@ void main() {
188188
);
189189
store = mergeLiveChannelWindowEvent(
190190
store,
191-
_summary('root', replyCount: 1, participants: ['p1']),
191+
_summary('root', replyCount: 1, participants: ['p1'], createdAt: 11),
192192
isTimelineRow: false,
193193
);
194194
store = mergeLiveChannelWindowEvent(
195195
store,
196-
_summary('root', replyCount: 2, participants: ['p1', 'p2']),
196+
_summary(
197+
'root',
198+
replyCount: 2,
199+
participants: ['p1', 'p2'],
200+
createdAt: 12,
201+
),
197202
isTimelineRow: false,
198203
);
199204

200205
expect(channelWindowThreadSummaries(store)['root']?.replyCount, 2);
201206
});
202207

208+
test('an older or equal-time live summary cannot replace a newer one', () {
209+
var store = replaceNewestChannelWindow(
210+
const ChannelWindowStore.empty(),
211+
_page(rows: [_row('root', createdAt: 10)]),
212+
);
213+
store = mergeLiveChannelWindowEvent(
214+
store,
215+
_summary('root', replyCount: 3, participants: ['p1'], createdAt: 30),
216+
isTimelineRow: false,
217+
);
218+
final afterOlder = mergeLiveChannelWindowEvent(
219+
store,
220+
_summary('root', replyCount: 1, participants: ['p1'], createdAt: 29),
221+
isTimelineRow: false,
222+
);
223+
final afterEqual = mergeLiveChannelWindowEvent(
224+
afterOlder,
225+
_summary('root', replyCount: 2, participants: ['p1'], createdAt: 30),
226+
isTimelineRow: false,
227+
);
228+
229+
expect(identical(afterOlder, store), isTrue);
230+
expect(identical(afterEqual, store), isTrue);
231+
expect(channelWindowThreadSummaries(afterEqual)['root']?.replyCount, 3);
232+
});
233+
203234
test('a refetched row outranks the live entry it duplicates', () {
204235
var store = replaceNewestChannelWindow(
205236
const ChannelWindowStore.empty(),
@@ -215,16 +246,23 @@ void main() {
215246
// so the stale live entry must not shadow it.
216247
final refreshed = replaceNewestChannelWindow(
217248
store,
218-
_pageWithThreads(
219-
rows: [_row('root', createdAt: 10)],
220-
threads: {
221-
'root': const ChannelWindowThreadSummary(
222-
replyCount: 5,
223-
descendantCount: 5,
224-
lastReplyAt: 12,
225-
participantPubkeys: ['p1'],
249+
ChannelWindowPage(
250+
startCursor: null,
251+
rows: [
252+
ChannelWindowRow(
253+
event: _row('root', createdAt: 10),
254+
thread: const ChannelWindowThreadSummary(
255+
replyCount: 5,
256+
descendantCount: 5,
257+
lastReplyAt: 12,
258+
participantPubkeys: ['p1'],
259+
),
260+
threadSummaryCreatedAt: 20,
226261
),
227-
},
262+
],
263+
aux: const [],
264+
nextCursor: null,
265+
hasMore: false,
228266
),
229267
);
230268

@@ -306,24 +344,6 @@ ChannelWindowPage _page({
306344
);
307345
}
308346

309-
/// Like [_page], but with thread summaries attached to named rows — what a
310-
/// refetched page looks like once replies exist.
311-
ChannelWindowPage _pageWithThreads({
312-
required List<NostrEvent> rows,
313-
required Map<String, ChannelWindowThreadSummary> threads,
314-
}) {
315-
return ChannelWindowPage(
316-
startCursor: null,
317-
rows: [
318-
for (final row in rows)
319-
ChannelWindowRow(event: row, thread: threads[row.id]),
320-
],
321-
aux: const [],
322-
nextCursor: null,
323-
hasMore: false,
324-
);
325-
}
326-
327347
NostrEvent _row(String id, {int createdAt = 10}) => _event(
328348
id: id,
329349
createdAt: createdAt,
@@ -345,8 +365,10 @@ NostrEvent _summary(
345365
String rootId, {
346366
required int replyCount,
347367
required List<String> participants,
368+
int createdAt = 10,
348369
}) => _event(
349-
id: 'summary-$rootId',
370+
id: 'summary-$rootId-$createdAt-$replyCount',
371+
createdAt: createdAt,
350372
kind: EventKind.channelThreadSummary,
351373
tags: [
352374
['e', rootId],

0 commit comments

Comments
 (0)