Files
buzz/mobile/test/features/channels/timeline_message_test.dart
klopez4212 b1d60f98e2 Bring synced Solo chats and projects to mobile (#8337)
## Summary
Bring desktop Solo chats and project organization to mobile, with synced
collapsible sections, shared unread highlights and tab badges, agent
selection, shared search, native iOS creation sheets, and inline typing
bubbles that transition into replies.

Resolve Solo placement for every chat entry route, retain encrypted
organization snapshots for offline reading, and let users resume or
discard unfinished chat and project setup without deleting existing
messages.

### Related issue
Related: #6565; expandable agent transcripts remain separate work.

### Testing
- Fresh Solo read state seeds each active chat from its captured initial
last-message timestamp before exposing row/section/tab unread state.
Baselines survive intervening channel updates and reset across
identity/community boundaries while surviving read-state readiness
changes. Regressions cover multiple chats, events before read-state
readiness and during/after seeding, and identity changes; removing
either the seed or the display gate fails them.
- Chat completion reconciles a retained Solo-save journal even when
placement is already confirmed. False/throwing cleanup regressions
ensure the outer intent remains until reconciliation and only one
placement is published. Typing terminal-close loops remain bounded; the
retry budget resets after an uninterrupted eight-second health interval
or transport reconnect.
- Typing retry budgets reset after sustained recovery; invalid Solo
updates retain cached rows with a retry warning that survives failed
refreshes. Project names use the editors’ 120-grapheme limit, including
emoji and combining characters. Regression coverage exercises repeated
recovery, invalid live/refresh heads, and character-limit boundaries.
- Rebased onto current main, preserving the newer Search controls,
Huddle timeline filtering, and message-media layout.
- Failed project journal writes reload storage before claiming recovery
and reopen the entered name for retry. Typing subscription rejections
are caught; terminal closures clear stale indicators and retry with a
bounded backoff, canceled on disposal. Regression tests cover both
false/throwing storage writes and initial/late subscription rejection.
- Explicit ordinary destinations skip optional Solo lookup waits.
Generic destinations perform one bounded lookup in the destination
(search no longer duplicates it); an unavailable classification falls
back to ordinary sending per the product owner's explicit choice.
Positively identified Solo destinations use Solo providers.
- Terminal Solo subscription closure preserves cached rows and exposes
live-update Retry. Page coverage verifies warning visibility, usable
rows during recovery, and a subsequent terminal close. Removing the
warning or the immediate ordinary-route guard fails its regression.
- Generic channel entries share an ordinary default when Solo
classification is unavailable, per the requested product behavior. Known
Solo placement takes precedence; callers can explicitly require
unresolved placement to remain blocked. Bounded initial lookup preserves
known Solo deep-link routing.
- Dirty newest snapshots and offline-save warnings survive transport
reconnects; Retry persists that same event even if the relay returns an
older head. Community changes replace the service, and agent-directory
reconnect refresh remains intact.
- Pending-save discard reloads failed removals. Repeated reconnect
testing confirms typing subscriptions are released on provider rebuild
and disposal; removing the existing cleanup fails the regression.
- Ordinary Home/create routes explicitly preserve private-channel
sending during Solo failures; identified Solo sends use the Solo sender
and explicit unresolved routes remain fail-closed. Solo unread replies
beyond the initial 200-event page are loaded through the oldest-unread
boundary.
- Chat/project/agent cleanup reloads failed removals, retains
same-process recovery, and protects replaced records. False/throw
regressions verify retries do not duplicate creation or membership.
Route, unread, and cleanup guard-removal mutations each fail their
regression.
- Ordinary channels, DMs, and forums remain sendable when optional Solo
sync fails; explicit unresolved placement stays blocked. Controlled
cache races retain the newest verified snapshot, keep usable chats
visible, and retry offline persistence without stale writes. Both
protection-removal regressions fail as expected.
- Confirmed journal cleanup checks false/throwing removal and
exact-record identity. Interrupted agent choices are visible
immediately, identify the saved agent, and cover Resume/Later/Discard
with accessible name/key-fallback controls.
- Notification deep links preserve the contiguous history cursor;
same-second messages infer the newest agent consistently. Failed
offline-cache writes surface Retry, with false/throwing storage failures
and offline restart covered.
- Composite history cursors cover 350 same-second events plus older
history; removing the ID cursor makes the regression fail. Agent changes
now journal before granting access, with restart/failure and
Resume/Later/Discard widget coverage. Signed malformed profiles remain
isolated.
- Native iOS avatar tests passed on the simulator: visible-row loading,
three-request concurrency, streamed byte limits, response validation,
downsampling/pixel limits, cancellation, and visible avatar updates.
- Solo and Home share observed-event/read-marker logic. Widget coverage
verifies unread rows, collapsed-section indicators, the tab badge before
first Solo visit, message/thread reads, forced unread, and filtering
archived/nonmember/unplaced chats.
- Chat intent is saved before ownership and organization preflight;
tests cover interrupted ownership lookup and a disconnect while the
native creation form is open.
- Mobile analysis, formatting, file-size checks, and full mobile tests
passed at `1d4c41354`.
- Project creation persists its encrypted name/UUID before connectivity
checks or relay reads. Restart tests cover Resume/Later/Discard, scope
isolation, stale-intent rejection, and lost acknowledgements. Removing
the pre-network save makes all four production-flow regressions fail.
- Regression coverage includes notification/Activity routing, inline
replies, unknown-placement send protection, restart recovery/discard,
and encrypted offline cache isolation/refresh.
- Earlier feature build exercised on a physical iPhone with existing
account/community data; review follow-ups have not been reinstalled on
the device. UIKit agent-row accessibility checks passed on an iOS
simulator.
- Earlier cross-platform `just ci` stopped on the existing `buzz-acp`
test `signals_cancel_startup_turn_and_pending_stdin_without_hanging`
(process exit-code assertion); no Rust production changes are included
in this PR.

### Remaining review limitation
Agent discovery is bounded to 10 pages / 1,000 profiles with automatic
retries disabled. Owner-scoped discovery remains open because the
current relay ignores `#auth` filters; supporting that query requires a
relay change.

### Snapshots
Sample data, shared Flutter/Android surface. Native iOS uses platform
sheets and controls.

| Solo: projects and chats | New chat | Choose an agent |
| --- | --- | --- |
| <img
src="https://raw.githubusercontent.com/block/buzz/d9b29aa079a3b9a88e8ed89b70df8d6af06fa41b/pr-8337--01-solo.png"
width="240" alt="Solo with collapsible projects and chats" /> | <img
src="https://raw.githubusercontent.com/block/buzz/d9b29aa079a3b9a88e8ed89b70df8d6af06fa41b/pr-8337--02-new-chat.png"
width="240" alt="New chat form" /> | <img
src="https://raw.githubusercontent.com/block/buzz/d9b29aa079a3b9a88e8ed89b70df8d6af06fa41b/pr-8337--03-agent-picker.png"
width="240" alt="Agent selection list" /> |

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
2026-10-15 17:07:23 -04:00

1501 lines
42 KiB
Dart

import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:buzz/features/channels/channel_window.dart';
import 'package:buzz/features/channels/timeline_message.dart';
import 'package:buzz/shared/relay/relay.dart';
import '../../helpers/thread_ids.dart';
NostrEvent _textMsg({
required String id,
String pubkey = 'alice',
String content = 'hello',
int createdAt = 1000,
List<List<String>>? extraTags,
}) => NostrEvent(
id: id,
pubkey: pubkey,
createdAt: createdAt,
kind: EventKind.streamMessage,
tags: [
['h', 'ch1'],
...?extraTags,
],
content: content,
sig: '',
);
/// A reply message with proper root/reply e-tag markers.
NostrEvent _replyMsg({
required String id,
required String parentId,
String? rootId,
String pubkey = 'alice',
String content = 'reply',
int createdAt = 2000,
List<List<String>> extraTags = const [],
}) {
final root = rootId ?? parentId;
final eTags = parentId == root
? [
['e', root, '', 'reply'],
]
: [
['e', root, '', 'root'],
['e', parentId, '', 'reply'],
];
return _textMsg(
id: id,
pubkey: pubkey,
content: content,
createdAt: createdAt,
extraTags: [...eTags, ...extraTags],
);
}
NostrEvent _systemMsg({
required String id,
required Map<String, dynamic> payload,
int createdAt = 1000,
}) => NostrEvent(
id: id,
pubkey: 'relay',
createdAt: createdAt,
kind: EventKind.systemMessage,
tags: [
['h', 'ch1'],
],
content: jsonEncode(payload),
sig: '',
);
NostrEvent _deletion({
required String id,
required List<String> targets,
int createdAt = 2000,
}) => NostrEvent(
id: id,
pubkey: 'alice',
createdAt: createdAt,
kind: EventKind.deletion,
tags: [
['h', 'ch1'],
for (final t in targets) ['e', t],
],
content: '',
sig: '',
);
NostrEvent _nip29Deletion({
required String id,
required List<String> targets,
int createdAt = 2000,
}) => NostrEvent(
id: id,
pubkey: 'alice',
createdAt: createdAt,
kind: EventKind.nip29DeleteEvent,
tags: [
['h', 'ch1'],
for (final t in targets) ['e', t],
],
content: '',
sig: '',
);
NostrEvent _edit({
required String id,
required String targetId,
required String content,
int createdAt = 2000,
List<List<String>> extraTags = const [],
}) => NostrEvent(
id: id,
pubkey: 'alice',
createdAt: createdAt,
kind: EventKind.streamMessageEdit,
tags: [
['h', 'ch1'],
['e', targetId],
...extraTags,
],
content: content,
sig: '',
);
NostrEvent _reaction({
required String id,
required String targetId,
int createdAt = 2000,
String content = '👍',
List<List<String>> extraTags = const [],
}) => NostrEvent(
id: id,
pubkey: 'bob',
createdAt: createdAt,
kind: EventKind.reaction,
tags: [
['h', 'ch1'],
['e', targetId],
...extraTags,
],
content: content,
sig: '',
);
NostrEvent _huddleEvent({
required String id,
required int kind,
String pubkey = 'pk1',
int createdAt = 1000,
}) => NostrEvent(
id: id,
pubkey: pubkey,
createdAt: createdAt,
kind: kind,
tags: [
['h', 'ch1'],
],
content: jsonEncode({
'ephemeral_channel_id': '8d764100-fd8f-44cf-9c98-6d8fbd739b8c',
}),
sig: '',
);
void main() {
group('SystemEvent.fromContent', () {
test('parses all known event types', () {
final types = {
'member_joined': SystemEventType.memberJoined,
'member_left': SystemEventType.memberLeft,
'member_removed': SystemEventType.memberRemoved,
'topic_changed': SystemEventType.topicChanged,
'purpose_changed': SystemEventType.purposeChanged,
'channel_created': SystemEventType.channelCreated,
'channel_archived': SystemEventType.channelArchived,
'channel_unarchived': SystemEventType.channelUnarchived,
};
for (final entry in types.entries) {
final event = SystemEvent.fromContent(
jsonEncode({'type': entry.key, 'actor': 'pk1'}),
);
expect(event, isNotNull, reason: 'Failed for ${entry.key}');
expect(event!.type, entry.value);
expect(event.actorPubkey, 'pk1');
}
});
test('returns null for unknown type', () {
final event = SystemEvent.fromContent(
jsonEncode({'type': 'unknown_type'}),
);
expect(event, isNull);
});
test('returns null for invalid JSON', () {
expect(SystemEvent.fromContent('not json'), isNull);
});
test('returns null for wrong JSON field types', () {
expect(
SystemEvent.fromContent(
jsonEncode({
'type': ['member_joined'],
'actor': 123,
}),
),
isNull,
);
});
test('parses target, topic, and purpose fields', () {
final event = SystemEvent.fromContent(
jsonEncode({
'type': 'topic_changed',
'actor': 'pk1',
'target': 'pk2',
'topic': 'New topic',
'purpose': 'New purpose',
}),
);
expect(event, isNotNull);
expect(event!.targetPubkey, 'pk2');
expect(event.topic, 'New topic');
expect(event.purpose, 'New purpose');
});
});
group('SystemEvent.describe', () {
String resolve(String? pk) => pk == 'pk1' ? 'Alice' : 'Bob';
test('member_joined self', () {
final event = SystemEvent(
type: SystemEventType.memberJoined,
actorPubkey: 'pk1',
targetPubkey: 'pk1',
);
expect(event.describe(resolve), 'Alice joined the channel');
});
test('member_joined by other', () {
final event = SystemEvent(
type: SystemEventType.memberJoined,
actorPubkey: 'pk1',
targetPubkey: 'pk2',
);
expect(event.describe(resolve), 'Alice added Bob to the channel');
});
test('member_left', () {
final event = SystemEvent(
type: SystemEventType.memberLeft,
actorPubkey: 'pk1',
);
expect(event.describe(resolve), 'Alice left the channel');
});
test('member_removed', () {
final event = SystemEvent(
type: SystemEventType.memberRemoved,
actorPubkey: 'pk1',
targetPubkey: 'pk2',
);
expect(event.describe(resolve), 'Alice removed Bob from the channel');
});
test('topic_changed', () {
final event = SystemEvent(
type: SystemEventType.topicChanged,
actorPubkey: 'pk1',
topic: 'Release v2',
);
expect(
event.describe(resolve),
'Alice changed the topic to "Release v2"',
);
});
test('purpose_changed', () {
final event = SystemEvent(
type: SystemEventType.purposeChanged,
actorPubkey: 'pk1',
purpose: 'Daily standups',
);
expect(
event.describe(resolve),
'Alice changed the purpose to "Daily standups"',
);
});
// The relay reports a clear as a change carrying an empty string, so
// without the cleared branch this reads: changed the topic to "".
test('a blank topic or purpose reads as cleared', () {
for (final blank in [null, '', ' \n\t ']) {
expect(
SystemEvent(
type: SystemEventType.topicChanged,
actorPubkey: 'pk1',
topic: blank,
).describe(resolve),
'Alice cleared the topic',
);
expect(
SystemEvent(
type: SystemEventType.purposeChanged,
actorPubkey: 'pk1',
purpose: blank,
).describe(resolve),
'Alice cleared the purpose',
);
}
});
test('no caption announces empty quotes', () {
for (final value in [null, '', ' ', 'Real topic']) {
expect(
SystemEvent(
type: SystemEventType.topicChanged,
actorPubkey: 'pk1',
topic: value,
).describe(resolve),
isNot(contains('""')),
);
}
});
test('surrounding whitespace is trimmed out of the quotes', () {
expect(
SystemEvent(
type: SystemEventType.topicChanged,
actorPubkey: 'pk1',
topic: ' Release v2 ',
).describe(resolve),
'Alice changed the topic to "Release v2"',
);
});
test('channel_created', () {
final event = SystemEvent(
type: SystemEventType.channelCreated,
actorPubkey: 'pk1',
);
expect(event.describe(resolve), 'Alice created this channel');
});
test('channel_archived', () {
final event = SystemEvent(
type: SystemEventType.channelArchived,
actorPubkey: 'pk1',
);
expect(event.describe(resolve), 'Alice archived this channel');
});
test('channel_unarchived', () {
final event = SystemEvent(
type: SystemEventType.channelUnarchived,
actorPubkey: 'pk1',
);
expect(event.describe(resolve), 'Alice unarchived this channel');
});
test('huddle_started', () {
final event = SystemEvent(
type: SystemEventType.huddleStarted,
actorPubkey: 'pk1',
);
expect(event.describe(resolve), 'Alice started a huddle');
});
test('huddle_ended', () {
final event = SystemEvent(
type: SystemEventType.huddleEnded,
actorPubkey: 'pk1',
);
expect(event.describe(resolve), 'Alice ended the huddle');
});
});
group('formatTimeline', () {
test('channel filters include desktop huddle lifecycle event kinds', () {
expect(
EventKind.channelEventKinds,
containsAll([
EventKind.huddleStarted,
EventKind.huddleParticipantJoined,
EventKind.huddleParticipantLeft,
EventKind.huddleEnded,
]),
);
expect(
EventKind.channelTimelineContentKinds,
containsAll([EventKind.huddleStarted, EventKind.huddleEnded]),
);
});
test('passes through text messages', () {
final events = [
_textMsg(id: threadIdA, content: 'hello'),
_textMsg(id: 'b', content: 'world', createdAt: 1100),
];
final result = formatTimeline(events);
expect(result, hasLength(2));
expect(result[0].content, 'hello');
expect(result[1].content, 'world');
expect(result[0].isSystem, false);
expect(result[0].edited, false);
});
test('filters deleted messages', () {
final events = [
_textMsg(id: threadIdA, content: 'keep'),
_textMsg(id: 'b', content: 'delete', createdAt: 1100),
_deletion(id: 'd1', targets: ['b']),
];
final result = formatTimeline(events);
expect(result, hasLength(1));
expect(result[0].content, 'keep');
});
test('filters messages deleted via kind:9005 (Buzz-native)', () {
// Agents emit kind:9005 deletes via the CLI. Mobile must mirror desktop
// and treat 9005 as a deletion marker, otherwise agent-deleted messages
// stay rendered until manual refresh.
final events = [
_textMsg(id: threadIdA, content: 'keep'),
_textMsg(id: 'b', content: 'delete', createdAt: 1100),
_nip29Deletion(id: 'd1', targets: ['b']),
];
final result = formatTimeline(events);
expect(result, hasLength(1));
expect(result[0].content, 'keep');
});
test('applies edits', () {
final events = [
_textMsg(id: threadIdA, content: 'original'),
_edit(id: 'e1', targetId: threadIdA, content: 'edited'),
];
final result = formatTimeline(events);
expect(result, hasLength(1));
expect(result[0].content, 'edited');
expect(result[0].edited, true);
});
test('applies edit tags for custom emoji rendering', () {
final events = [
_textMsg(
id: threadIdA,
content: 'original :old:',
extraTags: [
['emoji', 'old', 'https://relay.example/old.png'],
],
),
_edit(
id: 'e1',
targetId: threadIdA,
content: 'edited :new:',
extraTags: [
['emoji', 'new', 'https://relay.example/new.png'],
],
),
];
final result = formatTimeline(events);
expect(result.single.content, 'edited :new:');
expect(
result.single.tags.any(
(tag) =>
tag.length >= 3 &&
tag[0] == 'emoji' &&
tag[1] == 'new' &&
tag[2] == 'https://relay.example/new.png',
),
isTrue,
);
expect(
result.single.tags.any(
(tag) =>
tag.length >= 3 &&
tag[0] == 'emoji' &&
tag[1] == 'old' &&
tag[2] == 'https://relay.example/old.png',
),
isFalse,
);
});
test('preserves custom emoji reaction image URL from emoji tag', () {
final messages = formatTimeline([
_textMsg(id: 'm1'),
_reaction(
id: threadIdR1,
targetId: 'm1',
content: ':shipit:',
extraTags: [
['emoji', 'shipit', 'https://relay.example/shipit.png'],
],
),
], currentPubkey: 'bob');
final reaction = messages.single.reactions.single;
expect(reaction.emoji, ':shipit:');
expect(reaction.emojiUrl, 'https://relay.example/shipit.png');
expect(reaction.reactedByCurrentUser, isTrue);
});
test('latest edit wins', () {
final events = [
_textMsg(id: threadIdA, content: 'v1'),
_edit(id: 'e1', targetId: threadIdA, content: 'v2', createdAt: 2000),
_edit(id: 'e2', targetId: threadIdA, content: 'v3', createdAt: 3000),
];
final result = formatTimeline(events);
expect(result[0].content, 'v3');
});
test('deleted edit is ignored', () {
final events = [
_textMsg(id: threadIdA, content: 'original'),
_edit(id: 'e1', targetId: threadIdA, content: 'edited'),
_deletion(id: 'd1', targets: ['e1']),
];
final result = formatTimeline(events);
expect(result[0].content, 'original');
expect(result[0].edited, false);
});
test('edit of deleted message is ignored', () {
final events = [
_textMsg(id: threadIdA, content: 'original'),
_edit(id: 'e1', targetId: threadIdA, content: 'edited'),
_deletion(id: 'd1', targets: [threadIdA]),
];
final result = formatTimeline(events);
expect(result, isEmpty);
});
test('system messages are parsed', () {
final events = [
_systemMsg(
id: 's1',
payload: {'type': 'channel_created', 'actor': 'pk1'},
),
];
final result = formatTimeline(events);
expect(result, hasLength(1));
expect(result[0].isSystem, true);
expect(result[0].systemEvent, isNotNull);
expect(result[0].systemEvent!.type, SystemEventType.channelCreated);
});
test('huddle room IDs normalize canonical uppercase UUIDs', () {
final event = NostrEvent(
id: 'upper',
pubkey: 'alice',
createdAt: 1000,
kind: EventKind.huddleStarted,
tags: const [],
content:
'{"ephemeral_channel_id":"8D764100-FD8F-44CF-9C98-6D8FBD739B8C"}',
sig: '',
);
expect(
SystemEvent.fromHuddleEvent(event)!.ephemeralChannelId,
'8d764100-fd8f-44cf-9c98-6d8fbd739b8c',
);
});
test('huddle start and end events render as system rows', () {
final result = formatTimeline([
_huddleEvent(id: 'h1', kind: EventKind.huddleStarted),
_huddleEvent(id: 'h2', kind: EventKind.huddleEnded, createdAt: 1100),
]);
expect(result, hasLength(2));
expect(result[0].isSystem, isTrue);
expect(result[0].systemEvent!.type, SystemEventType.huddleStarted);
expect(
result[0].systemEvent!.ephemeralChannelId,
'8d764100-fd8f-44cf-9c98-6d8fbd739b8c',
);
expect(result[1].isSystem, isTrue);
expect(result[1].systemEvent!.type, SystemEventType.huddleEnded);
expect(
result[1].systemEvent!.ephemeralChannelId,
'8d764100-fd8f-44cf-9c98-6d8fbd739b8c',
);
});
test('huddle participant events are lifecycle metadata only', () {
final result = formatTimeline([
_huddleEvent(id: 'h1', kind: EventKind.huddleParticipantJoined),
_huddleEvent(id: 'h2', kind: EventKind.huddleParticipantLeft),
]);
expect(result, isEmpty);
});
test('unknown system messages are dropped', () {
final events = [
_systemMsg(id: 's1', payload: {'type': 'unknown'}),
];
final result = formatTimeline(events);
expect(result, isEmpty);
});
test('malformed system messages are skipped safely', () {
final events = [
_systemMsg(
id: 's1',
payload: {
'type': ['member_joined'],
'actor': 123,
},
),
_textMsg(id: threadIdA, content: 'hello', createdAt: 1100),
];
final result = formatTimeline(events);
expect(result, hasLength(1));
expect(result[0].content, 'hello');
});
test('reactions and typing indicators are filtered out', () {
final events = [
_textMsg(id: threadIdA, content: 'hello'),
_reaction(id: threadIdR1, targetId: threadIdA),
NostrEvent(
id: 'typing1',
pubkey: 'bob',
createdAt: 1000,
kind: EventKind.typingIndicator,
tags: [
['h', 'ch1'],
],
content: '',
sig: '',
),
];
final result = formatTimeline(events);
expect(result, hasLength(1));
expect(result[0].content, 'hello');
});
test('preserves chronological order', () {
final events = [
_textMsg(id: threadIdA, content: 'first', createdAt: 1000),
_systemMsg(
id: 's1',
payload: {'type': 'member_joined', 'actor': 'pk1', 'target': 'pk1'},
createdAt: 1100,
),
_textMsg(id: 'b', content: 'second', createdAt: 1200),
];
final result = formatTimeline(events);
expect(result, hasLength(3));
expect(result[0].content, 'first');
expect(result[1].isSystem, true);
expect(result[2].content, 'second');
});
test('streamMessageV2 events are included', () {
final events = [
NostrEvent(
id: 'v2msg',
pubkey: 'alice',
createdAt: 1000,
kind: EventKind.streamMessageV2,
tags: [
['h', 'ch1'],
],
content: 'legacy message',
sig: '',
),
];
final result = formatTimeline(events);
expect(result, hasLength(1));
expect(result[0].content, 'legacy message');
});
test('streamMessageDiff events are included', () {
final events = [
NostrEvent(
id: 'diff1',
pubkey: 'alice',
createdAt: 1000,
kind: EventKind.streamMessageDiff,
tags: [
['h', 'ch1'],
],
content: '```diff\n-old\n+new\n```',
sig: '',
),
];
final result = formatTimeline(events);
expect(result, hasLength(1));
expect(result[0].content, contains('diff'));
});
});
group('NostrEvent.threadReference', () {
test('returns nulls for top-level message (no e-tags)', () {
final event = _textMsg(id: threadIdA);
final ref = event.threadReference;
expect(ref.parentId, isNull);
expect(ref.rootId, isNull);
});
test('returns nulls for e-tags without root/reply markers', () {
final event = _textMsg(
id: threadIdA,
extraTags: [
['e', 'target'],
],
);
final ref = event.threadReference;
expect(ref.parentId, isNull);
expect(ref.rootId, isNull);
});
test('parses direct reply to root (single reply marker)', () {
final event = _textMsg(
id: 'reply1',
extraTags: [
['e', threadIdRoot1, '', 'reply'],
],
);
final ref = event.threadReference;
expect(ref.parentId, threadIdRoot1);
expect(ref.rootId, threadIdRoot1);
});
test('parses nested reply (root + reply markers)', () {
final event = _textMsg(
id: 'reply2',
extraTags: [
['e', threadIdRoot1, '', 'root'],
['e', threadIdParent1, '', 'reply'],
],
);
final ref = event.threadReference;
expect(ref.parentId, threadIdParent1);
expect(ref.rootId, threadIdRoot1);
});
test('last reply tag wins when multiple exist', () {
final event = _textMsg(
id: 'reply3',
extraTags: [
['e', threadIdRoot1, '', 'root'],
['e', threadIdOldUnderscoreParent, '', 'reply'],
['e', threadIdNewUnderscoreParent, '', 'reply'],
],
);
final ref = event.threadReference;
expect(ref.parentId, threadIdNewUnderscoreParent);
expect(ref.rootId, threadIdRoot1);
});
});
group('formatTimeline threading', () {
test('root messages have null parentId and rootId', () {
final events = [_textMsg(id: threadIdA)];
final result = formatTimeline(events);
expect(result[0].parentId, isNull);
expect(result[0].rootId, isNull);
});
test('reply messages carry parentId and rootId', () {
final events = [
_textMsg(id: threadIdRoot1),
_replyMsg(id: threadIdR1, parentId: threadIdRoot1, createdAt: 2000),
];
final result = formatTimeline(events);
final reply = result.firstWhere((m) => m.id == threadIdR1);
expect(reply.parentId, threadIdRoot1);
expect(reply.rootId, threadIdRoot1);
});
test('nested reply has distinct parentId and rootId', () {
final events = [
_textMsg(id: threadIdRoot1),
_replyMsg(id: threadIdR1, parentId: threadIdRoot1, createdAt: 2000),
_replyMsg(
id: 'r2',
parentId: threadIdR1,
rootId: threadIdRoot1,
createdAt: 3000,
),
];
final result = formatTimeline(events);
final nested = result.firstWhere((m) => m.id == 'r2');
expect(nested.parentId, threadIdR1);
expect(nested.rootId, threadIdRoot1);
});
});
group('buildMainTimelineEntries', () {
test(
'Me keeps agent replies inline without duplicate thread summaries',
() {
final messages = formatTimeline([
_textMsg(id: 'root', createdAt: 1000),
_replyMsg(id: 'answer', parentId: 'root', createdAt: 2000),
_textMsg(id: 'followup', createdAt: 3000),
]);
final entries = buildMainTimelineEntries(messages, flat: true);
expect(entries.map((e) => e.message.id), [
'root',
'answer',
'followup',
]);
expect(entries.every((e) => e.summary == null), isTrue);
},
);
test('returns only root messages', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(id: threadIdR1, parentId: threadIdA, createdAt: 2000),
_textMsg(id: 'b', createdAt: 3000),
]);
final entries = buildMainTimelineEntries(messages);
expect(entries, hasLength(2));
expect(entries[0].message.id, threadIdA);
expect(entries[1].message.id, 'b');
});
test('includes broadcast replies in the main timeline', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(id: 'hidden', parentId: threadIdA, createdAt: 2000),
_replyMsg(
id: 'broadcast',
parentId: threadIdA,
createdAt: 3000,
extraTags: const [
['broadcast', '1'],
],
),
]);
final entries = buildMainTimelineEntries(messages);
expect(entries.map((entry) => entry.message.id), [
threadIdA,
'broadcast',
]);
});
test('root without replies has null summary', () {
final messages = formatTimeline([_textMsg(id: threadIdA)]);
final entries = buildMainTimelineEntries(messages);
expect(entries[0].summary, isNull);
});
test('root with replies has summary with correct count', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'bob',
createdAt: 2000,
),
_replyMsg(
id: 'r2',
parentId: threadIdA,
pubkey: 'carol',
createdAt: 3000,
),
]);
final entries = buildMainTimelineEntries(messages);
expect(entries, hasLength(1));
expect(entries[0].summary, isNotNull);
expect(entries[0].summary!.replyCount, 2);
expect(entries[0].summary!.threadHeadId, threadIdA);
expect(entries[0].summary!.lastReplyAt, 3000);
});
test('summary counts every loaded descendant, not only direct children', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(id: threadIdR1, parentId: threadIdA, createdAt: 2000),
_replyMsg(
id: 'r2',
parentId: threadIdR1,
rootId: threadIdA,
createdAt: 3000,
),
]);
final entries = buildMainTimelineEntries(messages);
// The root badge stands for the whole thread, so the reply to r1 counts
// towards threadIdA as well. This matches the relay's `descendant_count` and
// the desktop's `buildDescendantStatsByMessageId`.
expect(entries[0].summary!.replyCount, 2);
expect(entries[0].summary!.lastReplyAt, 3000);
});
test('summary has up to 3 unique participant pubkeys', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'bob',
createdAt: 2000,
),
_replyMsg(
id: 'r2',
parentId: threadIdA,
pubkey: 'carol',
createdAt: 3000,
),
_replyMsg(
id: 'r3',
parentId: threadIdA,
pubkey: 'bob',
createdAt: 4000,
),
_replyMsg(
id: 'r4',
parentId: threadIdA,
pubkey: 'dave',
createdAt: 5000,
),
_replyMsg(
id: 'r5',
parentId: threadIdA,
pubkey: 'eve',
createdAt: 6000,
),
]);
final entries = buildMainTimelineEntries(messages);
final participants = entries[0].summary!.participantPubkeys;
expect(participants, hasLength(3));
// Most recent unique: eve, dave, bob (r5, r4, r3 — carol skipped
// because bob at r3 comes before carol at r2 when walking backwards).
// Reversed to chronological order.
expect(participants, ['bob', 'dave', 'eve']);
});
test('system messages remain in entries (parentId is null)', () {
final events = [
_systemMsg(
id: 's1',
payload: {'type': 'channel_created', 'actor': 'pk1'},
createdAt: 500,
),
_textMsg(id: threadIdA, createdAt: 1000),
];
final messages = formatTimeline(events);
final entries = buildMainTimelineEntries(messages);
expect(entries, hasLength(2));
expect(entries[0].message.isSystem, true);
});
test('empty input returns empty', () {
expect(buildMainTimelineEntries([]), isEmpty);
});
});
group('buildMainTimelineEntries relay summary merge', () {
ChannelWindowThreadSummary relaySummary({
required int replyCount,
int? descendantCount,
int? lastReplyAt,
List<String> participantPubkeys = const ['zoe'],
}) => ChannelWindowThreadSummary(
replyCount: replyCount,
descendantCount: descendantCount ?? replyCount,
lastReplyAt: lastReplyAt,
participantPubkeys: participantPubkeys,
);
test('relay recount covers replies this client never loaded', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
]);
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
threadIdA: relaySummary(replyCount: 4, lastReplyAt: 9000),
},
);
expect(entries.single.summary!.replyCount, 4);
expect(entries.single.summary!.lastReplyAt, 9000);
expect(entries.single.summary!.participantPubkeys, ['zoe']);
});
test('a reply newer than the recount is added to the badge', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'bob',
createdAt: 2000,
),
_replyMsg(
id: 'r2',
parentId: threadIdA,
pubkey: 'carol',
createdAt: 3000,
),
]);
// The relay counted only r1 before r2 landed.
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
threadIdA: relaySummary(replyCount: 1, lastReplyAt: 2000),
},
);
expect(entries.single.summary!.replyCount, 2);
expect(entries.single.summary!.lastReplyAt, 3000);
});
test('a reply in the same second as the recount still counts', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'bob',
createdAt: 2000,
),
_replyMsg(
id: 'r2',
parentId: threadIdA,
pubkey: 'carol',
createdAt: 2000,
),
]);
// Relay timestamps have second precision, so an equal timestamp is no
// proof the recount already included the second reply.
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
threadIdA: relaySummary(replyCount: 1, lastReplyAt: 2000),
},
);
expect(entries.single.summary!.replyCount, 2);
});
test('a lost recount still leaves a badge from the local reply', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'bob',
createdAt: 2000,
),
]);
final entries = buildMainTimelineEntries(messages);
expect(entries.single.summary!.replyCount, 1);
expect(entries.single.summary!.participantPubkeys, ['bob']);
});
test('the relay recount wins when it is ahead of the loaded replies', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'bob',
createdAt: 2000,
),
]);
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
threadIdA: relaySummary(replyCount: 7, lastReplyAt: 8000),
},
);
expect(entries.single.summary!.replyCount, 7);
expect(entries.single.summary!.lastReplyAt, 8000);
});
test('a zero recount does not erase a locally seen reply', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'bob',
createdAt: 2000,
),
]);
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
threadIdA: relaySummary(replyCount: 0, lastReplyAt: null),
},
);
expect(entries.single.summary!.replyCount, 1);
expect(entries.single.summary!.lastReplyAt, 2000);
});
test('a locally seen nested reply raises its root badge', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'bob',
createdAt: 2000,
),
_replyMsg(
id: 'r2',
parentId: threadIdR1,
rootId: threadIdA,
pubkey: 'carol',
createdAt: 3000,
),
]);
// The recount for threadIdA predates r2, so only the locally seen nested reply
// can bring the root badge, time, and facepile up to date.
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
threadIdA: relaySummary(
replyCount: 1,
lastReplyAt: 2000,
participantPubkeys: const ['bob'],
),
},
);
final root = entries.firstWhere((entry) => entry.message.id == threadIdA);
expect(root.summary!.replyCount, 2);
expect(root.summary!.lastReplyAt, 3000);
expect(root.summary!.participantPubkeys, ['bob', 'carol']);
});
test('the relay half counts descendants, not direct replies', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
]);
// The relay reports both numbers. A thread of nested replies has a
// `reply_count` far below its `descendant_count`, and the badge stands
// for the whole thread.
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
threadIdA: relaySummary(
replyCount: 1,
descendantCount: 5,
lastReplyAt: 9000,
),
},
);
expect(entries.single.summary!.replyCount, 5);
});
test('relay direct replies are a lower bound for a broadcast row', () {
final messages = formatTimeline([
_textMsg(id: threadIdA),
_replyMsg(
id: 'broadcast',
parentId: threadIdA,
extraTags: const [
['broadcast', '1'],
],
),
]);
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
'broadcast': relaySummary(replyCount: 1, descendantCount: 0),
},
);
final summary = entries.last.summary!;
expect(summary.replyCount, 1);
expect(summary.isLowerBound, isTrue);
});
test('a nested reply badges the reply it answers', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'bob',
createdAt: 2000,
extraTags: const [
['broadcast', '1'],
],
),
_replyMsg(
id: 'r2',
parentId: threadIdR1,
rootId: threadIdA,
pubkey: 'carol',
createdAt: 3000,
),
]);
// The relay keys recounts by the outermost root, so r1 never gets one and
// its badge has to come from the locally seen nested reply.
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
threadIdA: relaySummary(replyCount: 1, lastReplyAt: 2000),
},
);
final byId = {for (final entry in entries) entry.message.id: entry};
expect(byId[threadIdA]!.summary!.replyCount, 2);
expect(byId[threadIdR1]!.summary!.replyCount, 1);
expect(byId[threadIdR1]!.summary!.participantPubkeys, ['carol']);
expect(byId[threadIdR1]!.summary!.lastReplyAt, 3000);
});
test('merged participants keep relay identities first, capped at 3', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'bob',
createdAt: 2000,
),
_replyMsg(
id: 'r2',
parentId: threadIdA,
pubkey: 'carol',
createdAt: 3000,
),
]);
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
threadIdA: relaySummary(
replyCount: 1,
lastReplyAt: 2000,
participantPubkeys: const ['zoe', 'yara'],
),
},
);
expect(entries.single.summary!.participantPubkeys, [
'zoe',
'yara',
'carol',
]);
});
test('a deleted reply does not hold the badge above the recount', () {
// The relay counts down on delete and re-emits the recount, so taking the
// larger count must not resurrect a deleted reply. `formatTimeline` drops
// it from the local half first, which is what keeps `max` honest here.
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'bob',
createdAt: 2000,
),
_replyMsg(
id: 'r2',
parentId: threadIdA,
pubkey: 'carol',
createdAt: 3000,
),
_deletion(id: 'd1', targets: ['r2']),
]);
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
threadIdA: relaySummary(replyCount: 1, lastReplyAt: 2000),
},
);
expect(entries.single.summary!.replyCount, 1);
expect(entries.single.summary!.lastReplyAt, 2000);
});
test('a participant in both halves is not listed twice', () {
final messages = formatTimeline([
_textMsg(id: threadIdA, createdAt: 1000),
_replyMsg(
id: threadIdR1,
parentId: threadIdA,
pubkey: 'BOB',
createdAt: 2000,
),
_replyMsg(
id: 'r2',
parentId: threadIdA,
pubkey: 'carol',
createdAt: 3000,
),
]);
final entries = buildMainTimelineEntries(
messages,
relaySummaries: {
threadIdA: relaySummary(
replyCount: 2,
lastReplyAt: 3000,
participantPubkeys: const ['carol', 'bob'],
),
},
);
expect(entries.single.summary!.participantPubkeys, ['carol', 'bob']);
});
});
group('groupMembershipTimelineEntries', () {
List<MainTimelineEntry> entries(List<NostrEvent> events) =>
buildMainTimelineEntries(formatTimeline(events));
test('groups consecutive additions by one actor within five minutes', () {
final grouped = groupMembershipTimelineEntries(
entries([
_systemMsg(
id: threadIdA,
payload: {
'type': 'member_joined',
'actor': 'alice',
'target': 'bob',
},
createdAt: 1000,
),
_systemMsg(
id: 'b',
payload: {
'type': 'member_joined',
'actor': 'alice',
'target': 'carol',
},
createdAt: 1060,
),
_systemMsg(
id: 'c',
payload: {
'type': 'member_joined',
'actor': 'alice',
'target': 'dave',
},
createdAt: 1300,
),
]),
);
expect(grouped, hasLength(1));
expect(grouped.single.map((entry) => entry.message.id), [
threadIdA,
'b',
'c',
]);
});
test('groups self-joins from different people', () {
final grouped = groupMembershipTimelineEntries(
entries([
_systemMsg(
id: threadIdA,
payload: {
'type': 'member_joined',
'actor': 'alice',
'target': 'alice',
},
createdAt: 1000,
),
_systemMsg(
id: 'b',
payload: {'type': 'member_joined', 'actor': 'bob', 'target': 'bob'},
createdAt: 1060,
),
]),
);
expect(grouped.single, hasLength(2));
});
test('uses a fixed window anchored on the newest addition', () {
final grouped = groupMembershipTimelineEntries(
entries([
_systemMsg(
id: threadIdA,
payload: {
'type': 'member_joined',
'actor': 'alice',
'target': 'bob',
},
createdAt: 1000,
),
_systemMsg(
id: 'b',
payload: {
'type': 'member_joined',
'actor': 'alice',
'target': 'carol',
},
createdAt: 1240,
),
_systemMsg(
id: 'c',
payload: {
'type': 'member_joined',
'actor': 'alice',
'target': 'dave',
},
createdAt: 1301,
),
]),
);
expect(grouped.map((group) => group.length), [1, 2]);
});
test('actor changes, messages, and day boundaries break groups', () {
final dayOne =
DateTime(2026, 7, 14, 23, 59).millisecondsSinceEpoch ~/ 1000;
final dayTwo = DateTime(2026, 7, 15).millisecondsSinceEpoch ~/ 1000;
final grouped = groupMembershipTimelineEntries(
entries([
_systemMsg(
id: threadIdA,
payload: {
'type': 'member_joined',
'actor': 'alice',
'target': 'bob',
},
createdAt: dayOne,
),
_systemMsg(
id: 'b',
payload: {
'type': 'member_joined',
'actor': 'carol',
'target': 'dave',
},
createdAt: dayOne + 30,
),
_textMsg(id: 'message', createdAt: dayOne + 40),
_systemMsg(
id: 'c',
payload: {
'type': 'member_joined',
'actor': 'carol',
'target': 'erin',
},
createdAt: dayOne + 50,
),
_systemMsg(
id: 'd',
payload: {
'type': 'member_joined',
'actor': 'carol',
'target': 'frank',
},
createdAt: dayTwo,
),
]),
);
expect(grouped.map((group) => group.length), [1, 1, 1, 1, 1]);
});
});
}