Files
buzz/mobile/lib/features/forum/forum_thread_page.dart
Logan Johnson 82656ffea0 fix(mobile): standardize public-key identity display on npub (#7493)
🤖

## Summary

In the mobile app, anyone who hasn't set a display name shows up as a
raw 64-character hex key (e.g. `3a5d4f9c…`) — unreadable, and
unrecognizable as the same identity across screens. Profile and Settings
also let you copy that raw hex. Nostr public keys have a standard
readable form — `npub1…`, the same encoding other Nostr apps and our
desktop app already display. This PR makes every mobile identity surface
render npub instead:

- **Unnamed people everywhere** — message and thread authors, reactions,
typing indicators, member lists, channel details, DM headers and tiles,
inbox, search, forum cards, Pulse notes and reply context, mention
suggestions, and invite rows — now show a compact npub label: first 8 +
last 4 characters of the full npub joined by an ellipsis
(`npub1abcd…wxyz`), the same truncation desktop uses. Previously these
showed truncated raw hex.
- **DM fallback avatars and blank names** — 1:1 DM tiles and headers key
their fallback avatar to the same non-self counterpart the label names,
including self-first participant order; a self-DM keeps its
hex-key-derived initial. Blank or whitespace-only display names fall
back to the compact npub instead of rendering empty, while nonblank
authored names render verbatim (padding included).
- **Profile sheet → "Copy public key"** now copies the full canonical
npub — never raw hex. When the identity string isn't a valid public key,
the copy tile is disabled, so a malformed key never reaches the
clipboard.
- **Settings → Identity (pubkey)** displays and copies the full npub; an
invalid identity reads "Identity unavailable" with copy disabled.
- **Invalid identities never leak truncated raw hex** into the UI
anywhere — they render a neutral "Unknown identity" label.
- **Unchanged on purpose:** display names and verified handles (NIP-05 —
the `name@domain` badge) still render as before. Unnamed avatars keep
distinct per-key initials, derived from the underlying hex key rather
than the npub — otherwise every unnamed key would render the same "N"
initial. Event IDs are not public keys, so they keep their hex
truncation (in Pulse's "Replying to", the parent author shows npub while
an event-id fallback still shows hex). The nevent share link, private
keys, and internal hex storage are untouched. Inputs that accept a key
(invite/member entry) accept both hex and npub and keep working in hex
internally.

### Related issue

N/A. Searched open issues/PRs for npub identity display on mobile —
closest related: none found. Desktop's parallel npub standardization
lives in the stacked desktop PRs (#7488 foundation, #7489 controls,
#7495 display surfaces); this is the independent mobile slice (based
directly on `main`, not on those branches).

### Testing

At exact head `5a620e420a1fd57d9d8011ac26434eed32fcf765` (base: `main`
`44316ff72`; 40 files, +1,345/−154):

- Full mobile suite: 2,098 tests passing (`cd mobile && flutter test`);
`flutter analyze` clean; `dart format --set-exit-if-changed .` clean —
the same checks CI runs.
- Widget/unit coverage at production seams: compact labels and hex-keyed
avatar initials for DM headers/tiles, member rows, mention suggestions,
and Pulse reply context; DM fallback avatars keyed to the labeled
counterpart (self-first order and self-DMs); blank/whitespace
display-name npub fallback with nonblank authored labels verbatim,
including the Activity inbox sender and profile-sheet heading (each with
its own empty/whitespace production-seam regression); full-npub copy and
disabled-copy semantics in profile and settings; invalid-key
suppression; and hex↔npub input round-trips.

Verified via unit and widget tests — no device/simulator validation is
claimed.

### Task provenance

Buzz channel: `1f0e4a3d-7e01-4efe-bb16-843b357f85c9`

Task:
buzz://message?channel=1f0e4a3d-7e01-4efe-bb16-843b357f85c9&id=86b34eb4bd84a1472419e9af22636c011c0fe273e3c196f967d7a36996e149b6

---------

Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
2026-09-09 14:08:24 -04:00

674 lines
21 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../shared/mentions/agent_identity_provider.dart';
import '../../shared/theme/theme.dart';
import '../../shared/widgets/avatar_image.dart';
import '../../shared/widgets/buzz_loading_indicator.dart';
import '../../shared/widgets/frosted_app_bar.dart';
import '../../shared/widgets/frosted_scaffold.dart';
import '../../shared/widgets/modal_presentation.dart';
import '../channels/compose_bar.dart';
import '../channels/message_content.dart';
import '../../shared/profile/user_cache_provider.dart';
import '../../shared/utils/string_utils.dart';
import '../../shared/profile/user_profile.dart';
import '../profile/user_profile_sheet.dart';
import 'forum_models.dart';
import 'forum_provider.dart';
/// Full-screen page showing a forum post and its replies.
class ForumThreadPage extends HookConsumerWidget {
final String channelId;
final String postEventId;
final String? currentPubkey;
final bool isMember;
final bool isArchived;
const ForumThreadPage({
super.key,
required this.channelId,
required this.postEventId,
required this.currentPubkey,
required this.isMember,
required this.isArchived,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final threadAsync = ref.watch(
forumThreadProvider((channelId: channelId, eventId: postEventId)),
);
// Periodic refresh (every 10s, matching desktop).
useEffect(() {
final timer = Stream.periodic(const Duration(seconds: 10)).listen((_) {
ref.invalidate(
forumThreadProvider((channelId: channelId, eventId: postEventId)),
);
});
return timer.cancel;
}, [channelId, postEventId]);
final isOwnPost =
threadAsync
.whenData(
(t) =>
currentPubkey != null &&
t.post.pubkey.toLowerCase() == currentPubkey!.toLowerCase(),
)
.value ??
false;
return FrostedScaffold(
appBar: FrostedAppBar(
title: const Text('Thread'),
actions: [
if (isOwnPost)
IconButton(
onPressed: () =>
_showPostActions(context, ref, threadAsync.value!),
tooltip: 'Post actions',
icon: const Icon(LucideIcons.ellipsis),
),
],
),
body: threadAsync.when(
loading: () => Padding(
padding: EdgeInsets.only(top: frostedAppBarHeight(context)),
child: const Center(
child: BuzzLoadingIndicator(
size: 44,
semanticLabel: 'Loading thread',
),
),
),
error: (e, _) => Padding(
padding: EdgeInsets.only(top: frostedAppBarHeight(context)),
child: Center(
child: Text(
'Failed to load thread',
style: context.textTheme.bodyMedium?.copyWith(
color: context.colors.error,
),
),
),
),
data: (thread) => _ThreadContent(
thread: thread,
channelId: channelId,
currentPubkey: currentPubkey,
isMember: isMember,
isArchived: isArchived,
),
),
);
}
void _showPostActions(
BuildContext context,
WidgetRef ref,
ForumThreadResponse thread,
) {
showBuzzModalBottomSheet<void>(
context: context,
showDragHandle: true,
builder: (sheetContext) => SafeArea(
child: IconTheme.merge(
data: const IconThemeData(size: 22),
child: Padding(
padding: const EdgeInsets.fromLTRB(
Grid.gutter,
0,
Grid.gutter,
Grid.xs,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: const Icon(LucideIcons.copy),
title: const Text('Copy text'),
onTap: () {
Navigator.of(sheetContext).pop();
Clipboard.setData(ClipboardData(text: thread.post.content));
},
),
ListTile(
leading: Icon(
LucideIcons.trash2,
color: sheetContext.colors.error,
),
title: Text(
'Delete post',
style: TextStyle(color: sheetContext.colors.error),
),
onTap: () {
Navigator.of(sheetContext).pop();
_confirmDeletePost(context, ref, thread.post.eventId);
},
),
],
),
),
),
),
);
}
void _confirmDeletePost(BuildContext context, WidgetRef ref, String eventId) {
showBuzzDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('Delete post'),
content: const Text('This cannot be undone.'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () async {
Navigator.of(dialogContext).pop();
await deleteForumEvent(
ref,
channelId: channelId,
eventId: eventId,
);
if (context.mounted) {
Navigator.of(context).pop();
}
},
style: FilledButton.styleFrom(
backgroundColor: dialogContext.colors.error,
),
child: const Text('Delete'),
),
],
),
);
}
}
class _ThreadContent extends HookConsumerWidget {
final ForumThreadResponse thread;
final String channelId;
final String? currentPubkey;
final bool isMember;
final bool isArchived;
const _ThreadContent({
required this.thread,
required this.channelId,
required this.currentPubkey,
required this.isMember,
required this.isArchived,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
// Background media delivery may outlive this route's WidgetRef.
final providerContainer = ProviderScope.containerOf(context, listen: false);
final forumDelivery = ForumEventDelivery.capture(providerContainer);
final post = thread.post;
final replies = thread.replies;
// Preload profiles for all participants and tagged mentions.
final allPubkeys = useMemoized(() {
final pks = <String>{
post.pubkey.toLowerCase(),
...post.mentionPubkeys.map((pubkey) => pubkey.toLowerCase()),
};
for (final reply in replies) {
pks
..add(reply.pubkey.toLowerCase())
..addAll(reply.mentionPubkeys.map((pubkey) => pubkey.toLowerCase()));
}
return pks.toList()..sort();
}, [post, replies]);
final allPubkeysKey = allPubkeys.join('\u0000');
useEffect(() {
if (allPubkeys.isNotEmpty) {
ref.read(userCacheProvider.notifier).preload(allPubkeys);
}
return null;
}, [allPubkeysKey]);
return Column(
children: [
Expanded(
child: ListView(
padding: EdgeInsets.only(
top: frostedAppBarHeight(context),
bottom: Grid.xs,
),
children: [
_OriginalPost(post: post),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: Grid.gutter,
vertical: Grid.xxs,
),
child: Row(
children: [
Icon(
LucideIcons.messageSquare,
size: 16,
color: context.colors.onSurfaceVariant,
),
const SizedBox(width: Grid.half),
Text(
'${replies.length} ${replies.length == 1 ? 'reply' : 'replies'}',
style: context.textTheme.labelMedium?.copyWith(
color: context.colors.onSurfaceVariant,
fontWeight: FontWeight.w600,
),
),
],
),
),
// Reply list
if (replies.isEmpty)
Padding(
padding: const EdgeInsets.all(Grid.sm),
child: Text(
'No replies yet. Be the first to respond.',
style: context.textTheme.bodyMedium?.copyWith(
color: context.colors.onSurfaceVariant,
),
textAlign: TextAlign.center,
),
)
else
for (final reply in replies)
_ReplyRow(
reply: reply,
currentPubkey: currentPubkey,
channelId: channelId,
rootEventId: post.eventId,
),
],
),
),
// Reply composer
if (isMember && !isArchived)
ComposeBar(
channelId: channelId,
hintText: 'Reply to this post\u2026',
onSend:
(
content,
mentionPubkeys, {
mediaTags = const <List<String>>[],
}) => forumDelivery.createReply(
channelId: channelId,
parentEventId: post.eventId,
content: content,
mentionPubkeys: mentionPubkeys,
mediaTags: mediaTags,
),
),
],
);
}
}
class _OriginalPost extends ConsumerWidget {
final ForumPost post;
const _OriginalPost({required this.post});
@override
Widget build(BuildContext context, WidgetRef ref) {
final pk = post.pubkey.toLowerCase();
final profile =
ref.watch(userCacheProvider.select((cache) => cache[pk])) ??
ref.read(userCacheProvider.notifier).get(pk);
final displayName = profile?.label ?? shortPubkey(post.pubkey);
final userCache = ref.watch(userCacheProvider);
final agentMentionPubkeys = agentPubkeysWithProfileOwners(
knownAgentPubkeys: ref.watch(agentMentionPubkeysProvider(post.channelId)),
profileOwnedAgentPubkeys: [
for (final profile in userCache.values)
if (profile.ownerPubkey != null) profile.pubkey,
],
);
final mentionNames = mentionNamesWithDirectoryLabels(
mentionPubkeys: post.mentionPubkeys,
profileMentionNames: _buildMentionNames(post.mentionPubkeys, userCache),
directoryDisplayNames: ref.watch(agentDirectoryDisplayNamesProvider),
agentMentionPubkeys: agentMentionPubkeys,
);
return Padding(
padding: const EdgeInsets.all(Grid.xs),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
GestureDetector(
onTap: () => showUserProfileSheet(context, post.pubkey),
child: _Avatar(
key: ValueKey('forum-original-avatar-${post.eventId}'),
profile: profile,
pubkey: post.pubkey,
radius: 16,
isAgent: agentMentionPubkeys.contains(pk),
),
),
const SizedBox(width: Grid.xxs),
Expanded(
child: Row(
children: [
Expanded(
child: GestureDetector(
onTap: () => showUserProfileSheet(context, post.pubkey),
child: Text(
displayName,
maxLines: 1,
style: messageUsernameTextStyle,
overflow: TextOverflow.ellipsis,
),
),
),
const SizedBox(width: Grid.xxs),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: Grid.xxl),
child: Text(
formatRelativeTime(post.createdAt),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: messageTimestampTextStyle.copyWith(
color: context.colors.onSurfaceVariant,
),
),
),
],
),
),
],
),
const SizedBox(height: Grid.xxs),
MessageContent(
content: post.content,
mentionNames: mentionNames,
agentMentionPubkeys: agentMentionPubkeys,
tags: post.tags,
baseStyle: messageBodyTextStyle.copyWith(
color: context.colors.onSurface,
),
onMentionTap: (pubkey) => showUserProfileSheet(context, pubkey),
),
],
),
);
}
}
class _ReplyRow extends ConsumerWidget {
final ThreadReply reply;
final String? currentPubkey;
final String channelId;
final String rootEventId;
const _ReplyRow({
required this.reply,
required this.currentPubkey,
required this.channelId,
required this.rootEventId,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final pk = reply.pubkey.toLowerCase();
final profile =
ref.watch(userCacheProvider.select((cache) => cache[pk])) ??
ref.read(userCacheProvider.notifier).get(pk);
final displayName = profile?.label ?? shortPubkey(reply.pubkey);
final userCache = ref.watch(userCacheProvider);
final agentMentionPubkeys = agentPubkeysWithProfileOwners(
knownAgentPubkeys: ref.watch(agentMentionPubkeysProvider(channelId)),
profileOwnedAgentPubkeys: [
for (final profile in userCache.values)
if (profile.ownerPubkey != null) profile.pubkey,
],
);
final mentionNames = mentionNamesWithDirectoryLabels(
mentionPubkeys: reply.mentionPubkeys,
profileMentionNames: _buildMentionNames(reply.mentionPubkeys, userCache),
directoryDisplayNames: ref.watch(agentDirectoryDisplayNamesProvider),
agentMentionPubkeys: agentMentionPubkeys,
);
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: Grid.gutter,
vertical: Grid.xxs,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
GestureDetector(
onTap: () => showUserProfileSheet(context, reply.pubkey),
child: _Avatar(
key: ValueKey('forum-reply-avatar-${reply.eventId}'),
profile: profile,
pubkey: reply.pubkey,
radius: 12,
isAgent: agentMentionPubkeys.contains(pk),
),
),
const SizedBox(width: Grid.xxs),
Expanded(
child: Row(
children: [
Expanded(
child: GestureDetector(
onTap: () =>
showUserProfileSheet(context, reply.pubkey),
child: Text(
displayName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: messageUsernameTextStyle,
),
),
),
const SizedBox(width: Grid.xxs),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: Grid.xxl),
child: Text(
formatRelativeTime(reply.createdAt),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: messageTimestampTextStyle.copyWith(
color: context.colors.onSurfaceVariant,
),
),
),
],
),
),
SizedBox(
width: 28,
height: 28,
child: IconButton(
onPressed: () => _showActions(context, ref),
icon: Icon(
LucideIcons.ellipsis,
size: 16,
color: context.colors.onSurfaceVariant,
),
padding: EdgeInsets.zero,
visualDensity: VisualDensity.compact,
),
),
],
),
Padding(
padding: const EdgeInsets.only(left: 32, top: Grid.half),
child: MessageContent(
content: reply.content,
mentionNames: mentionNames,
agentMentionPubkeys: agentMentionPubkeys,
tags: reply.tags,
baseStyle: messageBodyTextStyle.copyWith(
color: context.colors.onSurface,
),
onMentionTap: (pubkey) => showUserProfileSheet(context, pubkey),
),
),
],
),
);
}
void _showActions(BuildContext context, WidgetRef ref) {
final isOwn =
currentPubkey != null &&
reply.pubkey.toLowerCase() == currentPubkey!.toLowerCase();
showBuzzModalBottomSheet<void>(
context: context,
showDragHandle: true,
builder: (sheetContext) => SafeArea(
child: IconTheme.merge(
data: const IconThemeData(size: 22),
child: Padding(
padding: const EdgeInsets.fromLTRB(
Grid.gutter,
0,
Grid.gutter,
Grid.xs,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: const Icon(LucideIcons.copy),
title: const Text('Copy text'),
onTap: () {
Navigator.of(sheetContext).pop();
Clipboard.setData(ClipboardData(text: reply.content));
},
),
if (isOwn)
ListTile(
leading: Icon(
LucideIcons.trash2,
color: sheetContext.colors.error,
),
title: Text(
'Delete reply',
style: TextStyle(color: sheetContext.colors.error),
),
onTap: () {
Navigator.of(sheetContext).pop();
_confirmDelete(context, ref);
},
),
],
),
),
),
),
);
}
void _confirmDelete(BuildContext context, WidgetRef ref) {
showBuzzDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('Delete reply'),
content: const Text('This cannot be undone.'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () async {
Navigator.of(dialogContext).pop();
await deleteForumEvent(
ref,
channelId: channelId,
eventId: reply.eventId,
rootEventId: rootEventId,
);
},
style: FilledButton.styleFrom(
backgroundColor: dialogContext.colors.error,
),
child: const Text('Delete'),
),
],
),
);
}
}
class _Avatar extends StatelessWidget {
final UserProfile? profile;
final String pubkey;
final double radius;
final bool isAgent;
const _Avatar({
super.key,
required this.profile,
required this.pubkey,
required this.radius,
required this.isAgent,
});
@override
Widget build(BuildContext context) {
final initial =
profile?.initial ?? (pubkey.isNotEmpty ? pubkey[0].toUpperCase() : '?');
final avatarUrl = profile?.avatarUrl;
return AvatarImage(
imageUrl: avatarUrl,
radius: radius,
backgroundColor: context.colors.primaryContainer,
fallback: Text(
initial,
style: TextStyle(
fontSize: radius * 0.75,
fontWeight: FontWeight.w600,
color: context.colors.onPrimaryContainer,
),
),
isAgent: isAgent,
);
}
}
Map<String, String> _buildMentionNames(
List<String> mentionPubkeys,
Map<String, UserProfile> userCache,
) {
final names = <String, String>{};
for (final pk in mentionPubkeys) {
final p = userCache[pk.toLowerCase()];
if (p?.displayName != null) {
names[pk.toLowerCase()] = p!.displayName!;
}
}
return names;
}