Files
buzz/mobile/test/features/forum/forum_widgets_test.dart
Taylor Ho 9d36778c37 feat(mobile): refactor Activity behavior and ui (#2889)
**Category:** improvement
**User Impact:** Mobile users can scan Activity as a focused
conversation inbox and open the exact unread message or thread
represented by each item.

## Context

Mobile's Activity tab had not kept pace with Desktop: it presented
isolated event headlines, advertised categories that were often empty,
and opened a channel without clearly landing on the selected item.

This PR brings the Mobile surface toward the conversation-oriented
direction explored in Clay Delk's Desktop [Inbox refactor PR
#2045](https://github.com/block/buzz/pull/2045), while adapting it to
Mobile rather than copying the Desktop split-pane implementation. The
related product/UX discussion is captured in the originating [Buzz
thread](buzz://message?channel=a9bbc0e5-d25d-4740-849c-93c34bb578a4&id=a7d9a4d33dcd8c6bf0dc67d81c328892b9e38dedaa8548920224ef388301b6ab).

## UX decisions in this PR

- **Conversation-oriented, not event-oriented:** related updates
collapse into one row per thread/DM conversation, represented by the
latest update and ordered by latest activity. Separate top-level
conversations in the same channel remain separate rows.
- **Resume at the oldest unread:** tapping a grouped row opens the
represented canonical message/thread/DM at its oldest unread item,
rather than merely opening the channel at an arbitrary position.
- **Desktop-aligned row hierarchy:** rows lead with a full avatar and
sender, followed by contextual location/type metadata, unread dot +
time, and a two-line preview. A **New** boundary separates unread and
read content.
- **Mobile-native navigation:** Mobile keeps a single-column `Activity →
canonical conversation → Back` flow. It does not introduce Desktop's
persistent detail pane.
- **Compact filtering:** the old horizontal chip rail becomes a compact
filter menu so the source set fits a phone viewport without horizontal
scanning. Filters are All, Mentions, Threads, Needs Action, Activity,
Agents, Reminders, and Drafts.
- **Focused source semantics:** All covers personally relevant work—DMs,
mentions, thread replies, needs-action events, owned-agent activity, due
reminders, and active drafts—rather than becoming a generic stream of
every channel message. Mobile's standalone Activity source is currently
limited to DM traffic because it does not have Desktop's aggregated
channel-activity feed.
- **Shared read behavior:** rows project canonical
channel/thread/message markers, support unread-only and mark-all-read,
and use local overrides only where canonical markers cannot represent an
item.
- **Reminders and drafts are real data:** reminders use the same
encrypted NIP-ER events as Desktop. Drafts persist device-local composer
state, restore on return, survive failed sends, and clear after
successful sends.
- **Explain navigation failures:** an unavailable destination produces
an explanatory message rather than silently doing nothing or falling
back to an unrelated channel position.

## Implementation summary

- Adds a Mobile inbox model for conversation grouping, category
priority, contextual labels, sorting, filtering, and oldest-unread
targets.
- Expands relay-backed sources for mentions, approvals, owned-agent
lifecycle events, and DM traffic.
- Adds fail-closed NIP-ER reminder decryption and device-local
compose-draft persistence.
- Redesigns Activity rows, boundaries, filters, unread controls, and
empty/loading states.
- Routes rows through Mobile's existing canonical channel/thread screens
with precise target IDs.
- Adds model, provider, widget, reminder, read-state, draft-lifecycle,
and deep-link coverage.

## Reproduction steps

1. Run Mobile and open **Activity**.
2. Confirm full avatars, sender-first rows, context labels, unread
indicators, timestamps, two-line previews, and the compact filter
control.
3. Open the filter menu and verify All, Mentions, Threads, Needs Action,
Activity, Agents, Reminders, and Drafts.
4. Tap a grouped thread row and confirm the canonical conversation opens
at its oldest unread message.
5. Mark rows read/unread, enable unread-only mode, and use
mark-all-read; confirm state agrees with the channel/thread destination.
6. Type without sending in a channel or thread, leave, and confirm the
draft appears in Activity and restores in the composer.

## Screenshots

| Before — merge-base `dd222a509` | After — PR head `52ad40aee` |
|---|---|
| <img width="1206" height="2622" alt="image"
src="https://github.com/user-attachments/assets/ae961b08-bf8a-4bd5-b487-f6321ae8d85b"
/> | <img width="1206" height="2622" alt="image"
src="https://github.com/user-attachments/assets/bcbe7ab0-552a-417c-9e85-7a85eb4592ee"
/> |

Recaptured on the same authenticated iPhone 17 simulator, account,
theme, and Activity view, at this PR's current merge-base (`dd222a509`)
and head (`52ad40aee`). Both frames were taken within a few minutes on
the same live feed, so the visible conversation set overlaps closely
(the recent Ned/Bart/Tommy items appear in both). The compared change is
the row *structure*: Before leads with an `@ Mention` headline over a
small inline avatar and a horizontal chip rail; After leads with a full
avatar, a compact `labelMedium` sender label, contextual "Mentioned in"
metadata, and a filter menu. The sender username now renders at the same
compact scale the old `@ Mention` label used.

## Verification

- Current rebased head: `5bd87f4f4` on `origin/main` at `dd222a509`;
GitHub reports the PR mergeable.
- `flutter analyze` — clean at `5bd87f4f4`.
- Full Mobile suite — 698 passed, 1 skipped, 4 failed; all four failures
reproduce identically on clean `origin/main` (`channels_page_test`
create-channel sheet and three `compose_bar_test` agent-mention cases).
- The prior PR-specific `home_page_test` failures were fixed by
providing the Activity local-state dependency in that harness.
- Independent code and simulator UI review — approved.
- Post-rebase GitHub checks are running.

---------

Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
Signed-off-by: npub14vtk7pvazqrq9639qu7e560wnqtl0d53ca4gjuvq6jzf3k2el23qqlwa7f <ab176f059d100602ea25073d9a69ee9817f7b691c76a897180d48498d959faa2@buzz.block.builderlab.xyz>
Co-authored-by: npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6w <52a228d6edf316ec6812ac3c9fc0d696ab59fc7954d77e7be31eedcddf91335b@buzz.block.builderlab.xyz>
Co-authored-by: npub14vtk7pvazqrq9639qu7e560wnqtl0d53ca4gjuvq6jzf3k2el23qqlwa7f <ab176f059d100602ea25073d9a69ee9817f7b691c76a897180d48498d959faa2@buzz.block.builderlab.xyz>
2026-07-27 16:55:24 +00:00

660 lines
19 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:buzz/features/channels/channel.dart';
import 'package:buzz/features/forum/forum_models.dart';
import 'package:buzz/features/forum/forum_post_card.dart';
import 'package:buzz/features/forum/forum_posts_view.dart';
import 'package:buzz/features/forum/forum_provider.dart';
import 'package:buzz/features/forum/forum_thread_page.dart';
import 'package:buzz/features/profile/profile_provider.dart';
import 'package:buzz/features/profile/user_cache_provider.dart';
import 'package:buzz/features/profile/user_profile.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:buzz/shared/theme/theme.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _channelId = 'forum-channel';
final _forumChannel = Channel(
id: _channelId,
name: 'design-forum',
channelType: 'forum',
visibility: 'open',
description: '',
createdBy: 'abc123',
createdAt: DateTime(2025),
memberCount: 5,
isMember: true,
);
ForumPost _makePost({
String eventId = 'post1',
String pubkey = 'alice',
String content = 'Hello forum',
int createdAt = 1000,
List<List<String>> tags = const [
['h', 'forum-channel'],
],
ForumThreadSummary? threadSummary,
}) => ForumPost(
eventId: eventId,
pubkey: pubkey,
content: content,
kind: 45001,
createdAt: createdAt,
channelId: _channelId,
tags: tags,
threadSummary: threadSummary,
);
const _aliceProfile = UserProfile(pubkey: 'alice', displayName: 'Alice');
void _setSurfaceSize(WidgetTester tester, Size size) {
tester.view.devicePixelRatio = 1.0;
tester.view.physicalSize = size;
}
Widget _buildPostCard({
required ForumPost post,
String? currentPubkey = 'self',
Map<String, UserProfile> users = const {},
VoidCallback? onTap,
void Function(String)? onDelete,
}) {
return ProviderScope(
overrides: [
userCacheProvider.overrideWith(() => _FakeUserCacheNotifier(users)),
],
child: MaterialApp(
theme: AppTheme.light(),
home: Scaffold(
body: ForumPostCard(
post: post,
currentPubkey: currentPubkey,
onTap: onTap ?? () {},
onDelete: onDelete,
),
),
),
);
}
Widget _buildPostsView({
required ForumPostsResponse postsResponse,
Channel? channel,
Map<String, UserProfile> users = const {},
}) {
final ch = channel ?? _forumChannel;
return ProviderScope(
overrides: [
userCacheProvider.overrideWith(() => _FakeUserCacheNotifier(users)),
profileProvider.overrideWith(() => _FakeProfileNotifier()),
forumPostsProvider(ch.id).overrideWith((ref) async => postsResponse),
relayClientProvider.overrideWithValue(
RelayClient(baseUrl: 'http://localhost:3000'),
),
],
child: MaterialApp(
theme: AppTheme.light(),
home: Scaffold(
body: ForumPostsView(channel: ch, currentPubkey: 'self'),
),
),
);
}
/// Shared mock prefs for the compose bar's draft store. Initialized in
/// [main].
late SharedPreferences _testPrefs;
Widget _buildThreadPage({
required ForumThreadResponse threadResponse,
String postEventId = 'post1',
String? currentPubkey = 'self',
bool isMember = true,
bool isArchived = false,
Map<String, UserProfile> users = const {},
}) {
return ProviderScope(
overrides: [
userCacheProvider.overrideWith(() => _FakeUserCacheNotifier(users)),
profileProvider.overrideWith(() => _FakeProfileNotifier()),
forumThreadProvider((
channelId: _channelId,
eventId: postEventId,
)).overrideWith((ref) async => threadResponse),
savedPrefsProvider.overrideWithValue(_testPrefs),
relayClientProvider.overrideWithValue(
RelayClient(baseUrl: 'http://localhost:3000'),
),
],
child: MaterialApp(
theme: AppTheme.light(),
home: ForumThreadPage(
channelId: _channelId,
postEventId: postEventId,
currentPubkey: currentPubkey,
isMember: isMember,
isArchived: isArchived,
),
),
);
}
void main() {
setUp(() async {
SharedPreferences.setMockInitialValues({});
_testPrefs = await SharedPreferences.getInstance();
});
group('ForumPostCard', () {
testWidgets('renders author name and content', (tester) async {
await tester.pumpWidget(
_buildPostCard(
post: _makePost(),
users: const {'alice': _aliceProfile},
),
);
await tester.pumpAndSettle();
expect(find.text('Alice'), findsOneWidget);
expect(find.text('Hello forum'), findsOneWidget);
});
testWidgets('shows truncated pubkey when no profile', (tester) async {
await tester.pumpWidget(
_buildPostCard(post: _makePost(pubkey: 'abcdef1234567890')),
);
await tester.pumpAndSettle();
expect(find.text('abcdef12\u2026'), findsOneWidget);
});
testWidgets('truncates long content', (tester) async {
final longContent = 'A' * 300;
await tester.pumpWidget(
_buildPostCard(post: _makePost(content: longContent)),
);
await tester.pumpAndSettle();
// Should show 200 chars + "..."
expect(find.textContaining('${'A' * 200}...'), findsOneWidget);
});
testWidgets('shows reply count with correct pluralization', (tester) async {
await tester.pumpWidget(
_buildPostCard(
post: _makePost(
threadSummary: const ForumThreadSummary(
replyCount: 1,
descendantCount: 1,
participants: [],
),
),
),
);
await tester.pumpAndSettle();
expect(find.text('1 reply'), findsOneWidget);
await tester.pumpWidget(
_buildPostCard(
post: _makePost(
threadSummary: const ForumThreadSummary(
replyCount: 5,
descendantCount: 5,
participants: [],
),
),
),
);
await tester.pumpAndSettle();
expect(find.text('5 replies'), findsOneWidget);
});
testWidgets('hides thread summary when reply count is 0', (tester) async {
await tester.pumpWidget(
_buildPostCard(
post: _makePost(
threadSummary: const ForumThreadSummary(
replyCount: 0,
descendantCount: 0,
participants: [],
),
),
),
);
await tester.pumpAndSettle();
expect(find.text('0 replies'), findsNothing);
});
testWidgets('calls onTap when tapped', (tester) async {
var tapped = false;
await tester.pumpWidget(
_buildPostCard(post: _makePost(), onTap: () => tapped = true),
);
await tester.pumpAndSettle();
await tester.tap(find.byType(ForumPostCard));
expect(tapped, isTrue);
});
testWidgets('keeps media previews non-interactive in the post list', (
tester,
) async {
var tapped = false;
const imageUrl = 'https://example.com/media/card.png';
await tester.pumpWidget(
_buildPostCard(
post: _makePost(
content: '![image]($imageUrl)',
tags: const [
['h', _channelId],
[
'imeta',
'url https://example.com/media/card.png',
'm image/png',
],
],
),
onTap: () => tapped = true,
),
);
await tester.pumpAndSettle();
final preview = find.byKey(
const ValueKey(
'message-media-image-preview:https://example.com/media/card.png',
),
);
await tester.tapAt(tester.getCenter(preview));
await tester.pumpAndSettle();
expect(tapped, isTrue);
expect(
find.byKey(const ValueKey('message-media-image-viewer')),
findsNothing,
);
});
testWidgets('long press opens action sheet with Copy text', (tester) async {
await tester.pumpWidget(_buildPostCard(post: _makePost()));
await tester.pumpAndSettle();
await tester.longPress(find.byType(ForumPostCard));
await tester.pumpAndSettle();
expect(find.text('Copy text'), findsOneWidget);
});
testWidgets('long press shows Delete only for own posts', (tester) async {
// Own post — Delete should appear.
await tester.pumpWidget(
_buildPostCard(
post: _makePost(pubkey: 'self'),
currentPubkey: 'self',
onDelete: (_) {},
),
);
await tester.pumpAndSettle();
await tester.longPress(find.byType(ForumPostCard));
await tester.pumpAndSettle();
expect(find.text('Delete post'), findsOneWidget);
// Dismiss sheet.
await tester.tapAt(Offset.zero);
await tester.pumpAndSettle();
// Other's post — Delete should NOT appear.
await tester.pumpWidget(
_buildPostCard(
post: _makePost(pubkey: 'other'),
currentPubkey: 'self',
onDelete: (_) {},
),
);
await tester.pumpAndSettle();
await tester.longPress(find.byType(ForumPostCard));
await tester.pumpAndSettle();
expect(find.text('Delete post'), findsNothing);
});
testWidgets('delete confirmation dialog triggers onDelete', (tester) async {
String? deletedId;
await tester.pumpWidget(
_buildPostCard(
post: _makePost(pubkey: 'self', eventId: 'evt-to-delete'),
currentPubkey: 'self',
onDelete: (id) => deletedId = id,
),
);
await tester.pumpAndSettle();
// Long press → action sheet.
await tester.longPress(find.byType(ForumPostCard));
await tester.pumpAndSettle();
// Tap Delete post.
await tester.tap(find.text('Delete post'));
await tester.pumpAndSettle();
// Confirmation dialog appears.
expect(find.text('This cannot be undone.'), findsOneWidget);
// Tap Delete button.
await tester.tap(find.widgetWithText(FilledButton, 'Delete'));
await tester.pumpAndSettle();
expect(deletedId, 'evt-to-delete');
});
});
group('ForumPostsView', () {
testWidgets('shows empty state for members', (tester) async {
await tester.pumpWidget(
_buildPostsView(postsResponse: const ForumPostsResponse(posts: [])),
);
await tester.pumpAndSettle();
expect(find.text('No posts yet'), findsOneWidget);
expect(
find.text('Start a discussion by creating the first post.'),
findsOneWidget,
);
});
testWidgets('shows empty state for non-members', (tester) async {
await tester.pumpWidget(
_buildPostsView(
postsResponse: const ForumPostsResponse(posts: []),
channel: Channel(
id: _channelId,
name: 'design-forum',
channelType: 'forum',
visibility: 'open',
description: '',
createdBy: 'abc123',
createdAt: DateTime(2025),
memberCount: 5,
isMember: false,
),
),
);
await tester.pumpAndSettle();
expect(find.text('Join this forum to create posts.'), findsOneWidget);
});
testWidgets('shows FAB for members', (tester) async {
await tester.pumpWidget(
_buildPostsView(postsResponse: const ForumPostsResponse(posts: [])),
);
await tester.pumpAndSettle();
expect(find.byType(FloatingActionButton), findsOneWidget);
expect(find.byTooltip('New post'), findsOneWidget);
});
testWidgets('hides FAB for non-members', (tester) async {
await tester.pumpWidget(
_buildPostsView(
postsResponse: const ForumPostsResponse(posts: []),
channel: Channel(
id: _channelId,
name: 'design-forum',
channelType: 'forum',
visibility: 'open',
description: '',
createdBy: 'abc123',
createdAt: DateTime(2025),
memberCount: 5,
isMember: false,
),
),
);
await tester.pumpAndSettle();
expect(find.byType(FloatingActionButton), findsNothing);
});
testWidgets('renders post list', (tester) async {
await tester.pumpWidget(
_buildPostsView(
postsResponse: ForumPostsResponse(
posts: [
_makePost(content: 'First post'),
_makePost(eventId: 'post2', content: 'Second post'),
],
),
users: const {'alice': _aliceProfile},
),
);
await tester.pumpAndSettle();
expect(find.text('First post'), findsOneWidget);
expect(find.text('Second post'), findsOneWidget);
});
});
group('ForumThreadPage', () {
testWidgets('shows original post and replies header', (tester) async {
await tester.pumpWidget(
_buildThreadPage(
threadResponse: ForumThreadResponse(
post: _makePost(content: 'Thread root'),
replies: const [],
totalReplies: 0,
),
users: const {'alice': _aliceProfile},
),
);
await tester.pumpAndSettle();
expect(find.text('Thread'), findsOneWidget); // App bar title
expect(find.text('0 replies'), findsOneWidget);
expect(
find.text('No replies yet. Be the first to respond.'),
findsOneWidget,
);
});
testWidgets('shows reply count with replies', (tester) async {
await tester.pumpWidget(
_buildThreadPage(
threadResponse: ForumThreadResponse(
post: _makePost(),
replies: [
const ThreadReply(
eventId: 'r1',
pubkey: 'bob',
content: 'Great post!',
kind: 45003,
createdAt: 2000,
channelId: _channelId,
tags: [
['h', _channelId],
],
depth: 1,
),
],
totalReplies: 1,
),
users: const {
'alice': _aliceProfile,
'bob': UserProfile(pubkey: 'bob', displayName: 'Bob'),
},
),
);
await tester.pumpAndSettle();
expect(find.text('1 reply'), findsOneWidget);
expect(find.text('Bob'), findsOneWidget);
});
testWidgets('shows compose bar for members', (tester) async {
await tester.pumpWidget(
_buildThreadPage(
threadResponse: ForumThreadResponse(
post: _makePost(),
replies: const [],
totalReplies: 0,
),
isMember: true,
),
);
await tester.pumpAndSettle();
expect(find.text('Reply to this post\u2026'), findsOneWidget);
});
testWidgets('renders media previews for forum posts', (tester) async {
const imageUrl = 'https://example.com/media/forum.png';
await tester.pumpWidget(
_buildThreadPage(
threadResponse: ForumThreadResponse(
post: _makePost(
content: '![image]($imageUrl)',
tags: const [
['h', _channelId],
[
'imeta',
'url https://example.com/media/forum.png',
'm image/png',
],
],
),
replies: const [],
totalReplies: 0,
),
users: const {'alice': _aliceProfile},
),
);
await tester.pumpAndSettle();
expect(
find.byKey(
const ValueKey(
'message-media-image-preview:https://example.com/media/forum.png',
),
),
findsOneWidget,
);
});
testWidgets('keeps tall forum image previews bounded inline', (
tester,
) async {
_setSurfaceSize(tester, const Size(400, 800));
addTearDown(() {
tester.view.resetPhysicalSize();
tester.view.resetDevicePixelRatio();
});
const imageUrl = 'https://example.com/media/forum-tall.png';
await tester.pumpWidget(
_buildThreadPage(
threadResponse: ForumThreadResponse(
post: _makePost(
content: '![image]($imageUrl)',
tags: const [
['h', _channelId],
[
'imeta',
'url https://example.com/media/forum-tall.png',
'm image/png',
'dim 1200x2400',
],
],
),
replies: const [],
totalReplies: 0,
),
users: const {'alice': _aliceProfile},
),
);
await tester.pumpAndSettle();
final preview = find.byKey(
const ValueKey(
'message-media-image-preview:https://example.com/media/forum-tall.png',
),
);
final size = tester.getSize(preview);
expect(size.height, closeTo(240, 0.1));
expect(size.width, closeTo(120, 0.1));
});
testWidgets('hides compose bar for non-members', (tester) async {
await tester.pumpWidget(
_buildThreadPage(
threadResponse: ForumThreadResponse(
post: _makePost(),
replies: const [],
totalReplies: 0,
),
isMember: false,
),
);
await tester.pumpAndSettle();
expect(find.text('Reply to this post\u2026'), findsNothing);
});
testWidgets('shows 3-dot in app bar for own post', (tester) async {
await tester.pumpWidget(
_buildThreadPage(
threadResponse: ForumThreadResponse(
post: _makePost(pubkey: 'self'),
replies: const [],
totalReplies: 0,
),
currentPubkey: 'self',
),
);
await tester.pumpAndSettle();
expect(find.byTooltip('Post actions'), findsOneWidget);
});
testWidgets('hides 3-dot in app bar for others post', (tester) async {
await tester.pumpWidget(
_buildThreadPage(
threadResponse: ForumThreadResponse(
post: _makePost(pubkey: 'alice'),
replies: const [],
totalReplies: 0,
),
currentPubkey: 'self',
),
);
await tester.pumpAndSettle();
expect(find.byTooltip('Post actions'), findsNothing);
});
});
}
class _FakeUserCacheNotifier extends UserCacheNotifier {
final Map<String, UserProfile> _users;
_FakeUserCacheNotifier(this._users);
@override
Map<String, UserProfile> build() => _users;
@override
UserProfile? get(String pubkey) => _users[pubkey.toLowerCase()];
}
class _FakeProfileNotifier extends ProfileNotifier {
@override
Future<UserProfile?> build() async =>
const UserProfile(pubkey: 'self', displayName: 'Self');
}