Skip to content

Commit c11964d

Browse files
npub12uu53ml9upy7ww9apmtv6vm0u8xlcldx7znsjvwgsr7uvy5g0kssw943cabrow
andcommitted
fix(mobile): count thread descendants in the badge merge
The merge added in the previous commit still missed a nested reply. The local half of the summary read only direct children (`childrenByParent[messageId]`) and the relay half read `reply_count`, which counts direct replies too. A reply to a reply therefore left the root badge, its last-reply time, and its facepile unchanged, which is the case the merge exists to cover. Count descendants on both halves instead. Locally, `_buildDescendantStats` attributes every loaded message to each ancestor on its parent chain, with a hop cap so a malformed chain cannot loop. From the relay, read `descendant_count`, which the recount already carries. This mirrors `buildDescendantStatsByMessageId` and `buildRelayThreadSummary` on desktop, so both clients now show the same number for the same thread. Co-authored-by: Tom Brow <[email protected]> Signed-off-by: Tom Brow <[email protected]>
1 parent 4e33566 commit c11964d

2 files changed

Lines changed: 145 additions & 45 deletions

File tree

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

Lines changed: 91 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -509,13 +509,9 @@ List<MainTimelineEntry> buildMainTimelineEntries(
509509
List<TimelineMessage> messages, {
510510
Map<String, ChannelWindowThreadSummary>? relaySummaries,
511511
}) {
512-
// Index direct children by parentId.
513-
final childrenByParent = <String, List<TimelineMessage>>{};
514-
for (final msg in messages) {
515-
final pid = msg.parentId;
516-
if (pid == null) continue;
517-
childrenByParent.putIfAbsent(pid, () => []).add(msg);
518-
}
512+
// Index descendant stats by ancestor, so a nested reply updates every summary
513+
// above it and not only the summary of its direct parent.
514+
final descendantStats = _buildDescendantStats(messages);
519515

520516
return [
521517
for (final msg in messages)
@@ -524,7 +520,7 @@ List<MainTimelineEntry> buildMainTimelineEntries(
524520
message: msg,
525521
summary: _buildSummary(
526522
msg.id,
527-
childrenByParent,
523+
descendantStats,
528524
relaySummaries?[msg.id],
529525
),
530526
),
@@ -547,12 +543,17 @@ bool _isBroadcastReply(TimelineMessage message) {
547543
/// the later reply time rather than letting one shadow the other. The facepile
548544
/// order is mobile's own (see [_mergeParticipants]) because this file already
549545
/// renders relay participants in the order the relay sent them.
546+
///
547+
/// Both halves count descendants, not direct replies: the relay's
548+
/// `descendant_count` and the locally assembled [_buildDescendantStats]. A badge
549+
/// on the main timeline stands for the whole thread under that message, so a
550+
/// reply to a reply has to raise it.
550551
ThreadSummary? _buildSummary(
551552
String messageId,
552-
Map<String, List<TimelineMessage>> childrenByParent,
553+
Map<String, _DescendantStats> descendantStats,
553554
ChannelWindowThreadSummary? relaySummary,
554555
) {
555-
final local = _buildLocalSummary(messageId, childrenByParent);
556+
final local = _buildLocalSummary(messageId, descendantStats);
556557
final relay = _buildRelaySummary(messageId, relaySummary);
557558
if (relay == null) return local;
558559
if (local == null) return relay;
@@ -575,38 +576,102 @@ ThreadSummary? _buildSummary(
575576
}
576577

577578
/// Summary assembled from the replies present in the loaded timeline.
579+
///
580+
/// Counts every loaded descendant, not only direct children, because the root
581+
/// badge in the main timeline stands for the whole thread. This mirrors the
582+
/// desktop's `buildSummaryForDirectReplies`, which reads the same descendant
583+
/// stats and reverses the newest-first participants to oldest-first.
578584
ThreadSummary? _buildLocalSummary(
579585
String messageId,
580-
Map<String, List<TimelineMessage>> childrenByParent,
586+
Map<String, _DescendantStats> descendantStats,
581587
) {
582-
final replies = childrenByParent[messageId];
583-
if (replies == null || replies.isEmpty) return null;
584-
585-
// Up to 3 most recent unique participants (walk backwards).
586-
final seen = <String>{};
587-
final participants = <String>[];
588-
for (var i = replies.length - 1; i >= 0 && participants.length < 3; i--) {
589-
final pk = replies[i].pubkey.toLowerCase();
590-
if (seen.add(pk)) participants.add(pk);
591-
}
588+
final stats = descendantStats[messageId];
589+
if (stats == null || stats.descendantCount == 0) return null;
592590

593591
return ThreadSummary(
594592
threadHeadId: messageId,
595-
replyCount: replies.length,
596-
participantPubkeys: participants.reversed.toList(),
597-
lastReplyAt: replies.last.createdAt,
593+
replyCount: stats.descendantCount,
594+
participantPubkeys: stats.recentParticipantsNewestFirst.reversed.toList(),
595+
lastReplyAt: stats.lastReplyAt,
598596
);
599597
}
600598

599+
/// Descendant count, last reply time, and recent participants for every message
600+
/// that has at least one loaded descendant.
601+
///
602+
/// Mirrors the desktop's `buildDescendantStatsByMessageId`
603+
/// (`desktop/src/features/messages/lib/threadPanel.ts`): each message is
604+
/// attributed to every ancestor on its parent chain, so a reply nested under a
605+
/// reply still counts towards the root it belongs to. Messages are visited
606+
/// newest first so the capped participant list keeps the most recent repliers.
607+
Map<String, _DescendantStats> _buildDescendantStats(
608+
List<TimelineMessage> messages,
609+
) {
610+
final messageById = <String, TimelineMessage>{
611+
for (final msg in messages) msg.id: msg,
612+
};
613+
final statsByMessageId = <String, _DescendantStats>{
614+
for (final msg in messages) msg.id: _DescendantStats(),
615+
};
616+
617+
// Oldest first, keeping the original order for messages sharing a timestamp,
618+
// then walked in reverse so participants are collected newest first.
619+
final ordered = List<int>.generate(messages.length, (index) => index)
620+
..sort((left, right) {
621+
final byCreatedAt = messages[left].createdAt.compareTo(
622+
messages[right].createdAt,
623+
);
624+
return byCreatedAt != 0 ? byCreatedAt : left.compareTo(right);
625+
});
626+
627+
for (var i = ordered.length - 1; i >= 0; i--) {
628+
final message = messages[ordered[i]];
629+
final participant = message.pubkey.toLowerCase();
630+
631+
// Cap the walk so a malformed parent chain (a cycle, for instance) cannot
632+
// spin forever.
633+
var ancestorId = message.parentId;
634+
var hops = 0;
635+
final maxHops = messages.length + 1;
636+
637+
while (ancestorId != null && hops < maxHops) {
638+
final ancestorStats = statsByMessageId[ancestorId];
639+
if (ancestorStats == null) break;
640+
641+
ancestorStats.descendantCount += 1;
642+
ancestorStats.lastReplyAt = _laterOf(
643+
ancestorStats.lastReplyAt,
644+
message.createdAt,
645+
);
646+
if (ancestorStats.recentParticipantsNewestFirst.length < 3 &&
647+
!ancestorStats.recentParticipantsNewestFirst.contains(participant)) {
648+
ancestorStats.recentParticipantsNewestFirst.add(participant);
649+
}
650+
651+
ancestorId = messageById[ancestorId]?.parentId;
652+
hops += 1;
653+
}
654+
}
655+
656+
return statsByMessageId;
657+
}
658+
659+
/// Mutable accumulator for [_buildDescendantStats].
660+
class _DescendantStats {
661+
int descendantCount = 0;
662+
int? lastReplyAt;
663+
final List<String> recentParticipantsNewestFirst = [];
664+
}
665+
601666
/// Summary from the relay's recount, or null when it reports no replies.
602667
ThreadSummary? _buildRelaySummary(
603668
String messageId,
604669
ChannelWindowThreadSummary? relaySummary,
605670
) {
606-
if (relaySummary == null || relaySummary.replyCount <= 0) return null;
671+
if (relaySummary == null || relaySummary.descendantCount <= 0) return null;
607672
return ThreadSummary(
608673
threadHeadId: messageId,
609-
replyCount: relaySummary.replyCount,
674+
replyCount: relaySummary.descendantCount,
610675
participantPubkeys: relaySummary.participantPubkeys.take(3).toList(),
611676
lastReplyAt: relaySummary.lastReplyAt,
612677
);

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

Lines changed: 54 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -827,17 +827,23 @@ void main() {
827827
expect(entries[0].summary!.lastReplyAt, 3000);
828828
});
829829

830-
test('summary counts only direct children, not nested replies', () {
831-
final messages = formatTimeline([
832-
_textMsg(id: 'a', createdAt: 1000),
833-
_replyMsg(id: 'r1', parentId: 'a', createdAt: 2000),
834-
_replyMsg(id: 'r2', parentId: 'r1', rootId: 'a', createdAt: 3000),
835-
]);
836-
837-
final entries = buildMainTimelineEntries(messages);
838-
// Only r1 is a direct child of a; r2 is a child of r1.
839-
expect(entries[0].summary!.replyCount, 1);
840-
});
830+
test(
831+
'summary counts every loaded descendant, not only direct children',
832+
() {
833+
final messages = formatTimeline([
834+
_textMsg(id: 'a', createdAt: 1000),
835+
_replyMsg(id: 'r1', parentId: 'a', createdAt: 2000),
836+
_replyMsg(id: 'r2', parentId: 'r1', rootId: 'a', createdAt: 3000),
837+
]);
838+
839+
final entries = buildMainTimelineEntries(messages);
840+
// The root badge stands for the whole thread, so the reply to r1 counts
841+
// towards 'a' as well. This matches the relay's `descendant_count` and
842+
// the desktop's `buildDescendantStatsByMessageId`.
843+
expect(entries[0].summary!.replyCount, 2);
844+
expect(entries[0].summary!.lastReplyAt, 3000);
845+
},
846+
);
841847

842848
test('summary has up to 3 unique participant pubkeys', () {
843849
final messages = formatTimeline([
@@ -881,11 +887,12 @@ void main() {
881887
group('buildMainTimelineEntries relay summary merge', () {
882888
ChannelWindowThreadSummary relaySummary({
883889
required int replyCount,
890+
int? descendantCount,
884891
int? lastReplyAt,
885892
List<String> participantPubkeys = const ['zoe'],
886893
}) => ChannelWindowThreadSummary(
887894
replyCount: replyCount,
888-
descendantCount: replyCount,
895+
descendantCount: descendantCount ?? replyCount,
889896
lastReplyAt: lastReplyAt,
890897
participantPubkeys: participantPubkeys,
891898
);
@@ -979,7 +986,7 @@ void main() {
979986
expect(entries.single.summary!.lastReplyAt, 2000);
980987
});
981988

982-
test('a nested reply does not inflate its root badge', () {
989+
test('a locally seen nested reply raises its root badge', () {
983990
final messages = formatTimeline([
984991
_textMsg(id: 'a', createdAt: 1000),
985992
_replyMsg(id: 'r1', parentId: 'a', pubkey: 'bob', createdAt: 2000),
@@ -992,15 +999,43 @@ void main() {
992999
),
9931000
]);
9941001

995-
// The relay counts direct replies in `reply_count`, so 'a' is at 1 even
996-
// though the thread has two events under it.
1002+
// The recount for 'a' predates r2, so only the locally seen nested reply
1003+
// can bring the root badge, time, and facepile up to date.
9971004
final entries = buildMainTimelineEntries(
9981005
messages,
999-
relaySummaries: {'a': relaySummary(replyCount: 1, lastReplyAt: 2000)},
1006+
relaySummaries: {
1007+
'a': relaySummary(
1008+
replyCount: 1,
1009+
lastReplyAt: 2000,
1010+
participantPubkeys: const ['bob'],
1011+
),
1012+
},
10001013
);
10011014

1002-
expect(entries.single.message.id, 'a');
1003-
expect(entries.single.summary!.replyCount, 1);
1015+
final root = entries.firstWhere((entry) => entry.message.id == 'a');
1016+
expect(root.summary!.replyCount, 2);
1017+
expect(root.summary!.lastReplyAt, 3000);
1018+
expect(root.summary!.participantPubkeys, ['bob', 'carol']);
1019+
});
1020+
1021+
test('the relay half counts descendants, not direct replies', () {
1022+
final messages = formatTimeline([_textMsg(id: 'a', createdAt: 1000)]);
1023+
1024+
// The relay reports both numbers. A thread of nested replies has a
1025+
// `reply_count` far below its `descendant_count`, and the badge stands
1026+
// for the whole thread.
1027+
final entries = buildMainTimelineEntries(
1028+
messages,
1029+
relaySummaries: {
1030+
'a': relaySummary(
1031+
replyCount: 1,
1032+
descendantCount: 5,
1033+
lastReplyAt: 9000,
1034+
),
1035+
},
1036+
);
1037+
1038+
expect(entries.single.summary!.replyCount, 5);
10041039
});
10051040

10061041
test('a nested reply badges the reply it answers', () {
@@ -1032,7 +1067,7 @@ void main() {
10321067
);
10331068

10341069
final byId = {for (final entry in entries) entry.message.id: entry};
1035-
expect(byId['a']!.summary!.replyCount, 1);
1070+
expect(byId['a']!.summary!.replyCount, 2);
10361071
expect(byId['r1']!.summary!.replyCount, 1);
10371072
expect(byId['r1']!.summary!.participantPubkeys, ['carol']);
10381073
expect(byId['r1']!.summary!.lastReplyAt, 3000);

0 commit comments

Comments
 (0)