Files
buzz/mobile/lib/features/activity/activity_page/inbox_row.dart
Tom Brow 52cbc61131 fix(mobile): name identity-link mention pills from their key (#9841)
Follow-up to [#9699 mention
typing](https://github.com/block/buzz/pull/9699), fixing two identity
problems found in its review.

**Identity-link pills name the key they open.** An edit writes each
mention as an identity link, `[@Name](nostr:npub1…)`, and every message
from any client draws such a link as a pill. Mobile showed the label
written in the link, so `[@Wes](nostr:<mallory>)` drew an ordinary
`@Wes` pill that opened Mallory's profile, and two namesakes in an
edited message both read `Scout`. The pill now shows the name its key
resolves to in the channel (with the namesake qualifier and agent icon),
as buzz-app's `ProfileMention` already does. The written label shows
only when the key has no name on this device (no profile, directory or
roster name), never a compact npub in its place. This holds whether or
not the link's key is also tagged. A pill requests its key's profile
when uncached, so a written label gives way to the key's name once it
loads.

Edits carry no `p` tag, so an identity-link pill resolves its own key.
In channel, thread and forum rows the pill watches that one key's
channel label (with the namesake qualifier and agent icon) and requests
the key's profile when it builds, so only links that actually draw a
pill cost a lookup, whatever Markdown surrounds them. Inbox and search
previews draw identity links the same way, taking keys from the preview
pieces they render. These keys never feed the text bindings, so plain
`@Name` text still binds only through signed tags.

**Typed names group the way the text scan reads them.** The composer
grouped the roster by `toLowerCase` while the scan folds names with
`foldMentionLabel`. With members `Sam` and `ſam`, typing `@ſam` sent
Sam's `p` tag. Grouping, lookup and the send-time key qualifier now all
fold, so namesakes under folding fail as ambiguous, as other namesakes
already do.

**Linked lookups stay current and bounded.** Pills and preview rows
request their keys through the profile cache's revalidation path. A name
restored from the last launch is revalidated, so a renamed key's link
shows its current name. A lookup that fails while offline is retried
once the relay reconnects, including when the reconnect comes while that
lookup is still on the wire. A key the relay says has no profile is not
asked for again for five minutes, and the cache remembers at most 1,000
such keys per community. Previews keep tilde and quoted code fences
literal and read blockquotes as the full message does, and load only the
links on lines they draw. Editing a message folds historical names the
way the scan does, so a name two tagged people share under folding seeds
no chip. Rendering binds signed names by the same fold, so with signed
`Sam` and `ſam` a plain `@Sam` stays text instead of drawing Sam's pill.

Desktop (buzz-app) already names identity-link chips from the key and
needs no change.

### Validation

Rows add no per-message work: message bodies are no longer scanned for
links. Each drawn identity-link pill adds one label watch for its own
key.

Added tests:
- [Channel page journey
step](mobile/test/features/channels/channel_detail_page_test.dart): an
edited message linking `[@Wes]` to Mallory's key draws `Mallory`, and
two edited `Scout` namesakes draw distinct qualified labels, through the
real channel row.
- [Channel page journey
step](mobile/test/features/channels/channel_detail_page_test.dart): a
link to a key with no name here keeps its written label.
- [Preview identity
link](mobile/test/features/channels/message_content/preview_text_test.dart):
an inbox/search preview shows the key's resolved name, or the written
label when unknown.
- [Preview
keys](mobile/test/features/channels/message_content/preview_text_test.dart):
a preview loads only links it draws (not ones in code or past its line
limit), including labels with brackets.

Full-app run (iOS simulator, debug build, signed in to a test
community): posted a message with a spoofed identity link, a link to a
key with no profile here, and a link inside inline code. The spoofed
link drew the key's real name as a pill and opened that person's
profile; the unknown key kept its written label; the code span stayed
raw. The same message drew matching pills in search results and in the
thread view.
- [Channel row
loads](mobile/test/features/channels/channel_detail_page_test.dart): a
row requests profiles only for links it draws as pills, not ones in a
quoted code fence or an HTML comment.
- [Folded chip
qualifiers](mobile/test/features/channels/compose_bar_test/exact_mention_tests.dart):
picked `@Sam` and `@ſam` chips both carry their keys on send.
- [Ambiguous typed names
table](mobile/test/features/channels/compose_bar_test/exact_mention_tests.dart):
`Sam` and `ſam` in either roster order now refuse `@ſam` as ambiguous.

- [Restart and reconnect
journey](mobile/test/features/channels/channel_detail_page_test.dart): a
restored old name and an offline first lookup both resolve after the
relay reconnects, on the same mounted pills, and a key with no profile
is not requested again.
- [Preview
fences](mobile/test/features/channels/message_content/preview_text_test.dart):
tilde and quoted fences keep links and Markdown literal and load no
keys.
- [Overtaken
lookup](mobile/test/shared/profile/user_cache_provider_test.dart): a
reconnect during a link's failing lookup asks once more after it
settles.
- [Folded signed
names](mobile/test/features/channels/message_content_exact_mentions_test.dart):
signed `Sam` and `ſam` in either tag order leave `@Sam` as text in the
message and its preview.
- [Folded edit
chips](mobile/test/features/channels/message_edit_sheet_test.dart):
`Sam` and `ſam` tagged in either order open as text, with no chip.
- [Non-member
labels](mobile/test/shared/identity_names/identity_names_test.dart): a
non-member labels the same with or without the roster shortcut,
including names shaped like qualifiers.

### Regressions

- **Performance:** rows do no new scanning; each drawn identity-link
pill adds one label watch. A non-member whose name can't collide no
longer re-resolves the whole roster.
- **Mention semantics:** unchanged for tagged mentions and plain text.
Only identity-link pills change, from the written label to the key's
resolved name.
- **Composer:** names that differ only under Unicode folding (`ſ`/`s`,
`µ`/`μ`, final `ς`/`σ`) are now one name when matching typed text, so a
typed one between two such members asks for a pick instead of silently
choosing one. Picked chips are unaffected.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz>
2026-11-20 17:21:54 -08:00

618 lines
24 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

part of '../activity_page.dart';
const _inboxSwipeActionInset = Grid.half;
const _inboxReminderPreviewLength = 100;
const _inboxSwipeActionLabelMinWidth = Grid.xxl;
const _inboxSwipeLabelRevealWidth =
_inboxSwipeActionLabelMinWidth + (_inboxSwipeActionInset * 2);
/// One conversation row, matching desktop's inbox item hierarchy:
/// avatar | sender + unread dot + time | contextual label | preview.
///
/// Swiping left reveals the row's read-state action. Opening remains a tap or
/// long-press action, so the swipe has one clear, easily recoverable outcome.
class _InboxRow extends HookConsumerWidget {
final InboxItem item;
final Channel? channel;
final String? currentPubkey;
final bool isDone;
final VoidCallback onTap;
final VoidCallback onMarkRead;
final VoidCallback onMarkUnread;
const _InboxRow({
super.key,
required this.item,
required this.channel,
required this.currentPubkey,
required this.isDone,
required this.onTap,
required this.onMarkRead,
required this.onMarkUnread,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
const restingRevealWidth = 132.0;
const commitThreshold = 0.58;
final revealAmount = useState(0.0);
final isDragging = useState(false);
final labelHapticFired = useRef(false);
final senderPubkey = item.item.pubkey.toLowerCase();
final mentionPubkeys = mentionedPubkeysFromTags(item.item.tags);
// Identity links name their own keys: resolve those for display only.
// Only links in the two-line preview render, so only those resolve.
final linkedPubkeys = useMemoized(
() => messagePreviewIdentityKeys(item.item.displayContent, maxLines: 2),
[item.item.displayContent],
);
final relevantPubkeys = {senderPubkey, ...mentionPubkeys, ...linkedPubkeys};
final profiles = <String, UserProfile?>{
for (final pubkey in relevantPubkeys)
pubkey: ref.watch(userCacheProvider.select((cache) => cache[pubkey])),
};
final profile = profiles[senderPubkey];
// The shared label contract: blank cached names (empty or whitespace-only
// are relay-valid) fall back to the compact npub, never a blank sender.
// Rows compare names within their own channel, like the channel itself.
final channelId = channel?.id ?? item.item.channelId;
final Map<String, String> contextualLabels;
if (channelId == null) {
// No channel: the row's own identities are the comparison context.
final names = watchIdentityNames(ref, relevantPubkeys);
requestLinkedProfiles(ref, linkedPubkeys);
contextualLabels = identityLabels(names, {
senderPubkey,
...mentionPubkeys,
}, linkedPubkeys);
} else {
contextualLabels = watchChannelIdentityLabels(ref, channelId, {
senderPubkey,
...mentionPubkeys,
}, linkedPubkeys: linkedPubkeys);
}
final senderLabel =
contextualLabels[senderPubkey] ??
profile?.label ??
shortPubkey(item.item.pubkey);
final profileMentionNames = {
for (final pubkey in mentionPubkeys)
if (profiles[pubkey]?.displayName?.trim().isNotEmpty == true)
pubkey: profiles[pubkey]!.displayName!.trim(),
};
final knownAgentPubkeys = channel == null
? ref.watch(knownAgentPubkeysProvider)
: ref.watch(agentMentionPubkeysProvider(channel!.id));
final isAgent =
knownAgentPubkeys.contains(senderPubkey) ||
profile?.ownerPubkey != null;
final agentMentionPubkeys = agentPubkeysWithProfileOwners(
knownAgentPubkeys: knownAgentPubkeys,
profileOwnedAgentPubkeys: [
for (final pubkey in {...mentionPubkeys, ...linkedPubkeys})
if (profiles[pubkey]?.ownerPubkey != null) pubkey,
],
);
final mentionNames = mentionNamesWithDirectoryLabels(
mentionPubkeys: mentionPubkeys,
profileMentionNames: profileMentionNames,
directoryDisplayNames: ref.watch(agentDirectoryDisplayNamesProvider),
agentMentionPubkeys: agentMentionPubkeys,
);
final isDm = channel?.isDm ?? false;
final channelName = channel != null && !isDm
? (channel!.name.isNotEmpty ? channel!.name : null)
: null;
final label = inboxTypeLabel(
item,
channelName: channelName,
isDm: isDm,
senderLabel: senderLabel,
);
final mutedColor = context.colors.onSurfaceVariant;
final labelColor = item.isActionRequired && !isDone
? context.colors.tertiary
: mutedColor;
final reducedMotion = MediaQuery.of(context).disableAnimations;
final swipeDirection = Directionality.of(context) == TextDirection.ltr
? 1.0
: -1.0;
void closeActions() => revealAmount.value = 0;
void toggleReadState() {
closeActions();
isDone ? onMarkUnread() : onMarkRead();
}
return LayoutBuilder(
builder: (context, constraints) {
final actionExtent = constraints.maxWidth;
final revealedWidth = revealAmount.value
.clamp(0, actionExtent)
.toDouble();
final actionColor = isDone
? context.colors.primary
: context.appColors.success;
return ClipRect(
child: Stack(
children: [
if (revealedWidth > 0)
PositionedDirectional(
top: 0,
end: 0,
bottom: 0,
width: revealedWidth,
child: Padding(
key: ValueKey('inbox-swipe-background-${item.id}'),
padding: const EdgeInsets.all(_inboxSwipeActionInset),
child: _InboxSwipeAction(
key: ValueKey('inbox-swipe-read-${item.id}'),
color: actionColor,
foregroundColor: contrastForeground(actionColor),
icon: isDone ? BuzzIcons.mail : BuzzIcons.mailOpen,
label: isDone ? 'Mark unread' : 'Mark as read',
onTap: toggleReadState,
),
),
),
AnimatedSlide(
offset: Offset(
-swipeDirection * revealAmount.value / constraints.maxWidth,
0,
),
duration: reducedMotion || isDragging.value
? Duration.zero
: const Duration(milliseconds: 160),
curve: Curves.easeOutCubic,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onHorizontalDragStart: (_) {
isDragging.value = true;
labelHapticFired.value = false;
},
onHorizontalDragUpdate: (details) {
isDragging.value = true;
final previous = revealAmount.value;
final next =
(previous - (details.delta.dx * swipeDirection))
.clamp(0, actionExtent)
.toDouble();
if (!labelHapticFired.value &&
previous < _inboxSwipeLabelRevealWidth &&
next >= _inboxSwipeLabelRevealWidth) {
labelHapticFired.value = true;
unawaited(HapticFeedback.selectionClick());
}
revealAmount.value = next;
},
onHorizontalDragEnd: (details) {
isDragging.value = false;
final velocity = details.primaryVelocity ?? 0;
final shouldCommit =
(velocity * swipeDirection) < -900 ||
revealAmount.value >= actionExtent * commitThreshold;
if (shouldCommit) {
toggleReadState();
} else {
revealAmount.value =
(velocity * swipeDirection) < -200 ||
revealAmount.value >= restingRevealWidth / 2
? restingRevealWidth
: 0;
}
},
child: Material(
color: context.colors.surface,
child: InkWell(
key: ValueKey('inbox-row-${item.id}'),
onTap: onTap,
onLongPress: () => _showRowActions(context, ref),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Grid.gutter,
vertical: Grid.twelve,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_RowAvatar(
pubkey: item.item.pubkey,
profile: profile,
isAgent: isAgent,
),
const SizedBox(width: messageAvatarContentGap),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Sender + unread dot + timestamp.
Row(
children: [
Expanded(
child: MessageAuthorMeta(
displayName: senderLabel,
username: messageUsernameLabel(
profile,
),
timestamp: _inboxTimestamp(
item.latestActivityAt,
),
nameColor: context.colors.onSurface,
metadataColor: mutedColor,
nameStyle: activityUsernameTextStyle,
timestampStyle:
activityTimestampTextStyle,
displayNameKey: ValueKey(
'activity-author-${item.id}',
),
usernameKey: ValueKey(
'activity-username-${item.id}',
),
timestampKey: ValueKey(
'activity-timestamp-${item.id}',
),
),
),
if (!isDone) ...[
const SizedBox(width: Grid.xxs),
Container(
key: ValueKey(
'inbox-unread-dot-${item.id}',
),
width: 6,
height: 6,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: context.colors.primary,
),
),
],
],
),
const SizedBox(height: Grid.quarter),
// Contextual label: "Mentioned in #channel" etc.
Row(
children: [
Flexible(
child: Text(
label.text,
style: activityContextTextStyle
.copyWith(color: labelColor),
overflow: TextOverflow.ellipsis,
),
),
if (label.channelLabel != null) ...[
const SizedBox(width: Grid.half),
Flexible(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal:
Grid.half + Grid.quarter,
vertical: Grid.quarter / 2,
),
decoration: BoxDecoration(
color: context
.colors
.surfaceContainerHighest,
borderRadius:
BorderRadius.circular(
Grid.half,
),
),
child: Text(
'#${label.channelLabel}',
style: activityContextTextStyle
.copyWith(color: mutedColor),
overflow: TextOverflow.ellipsis,
),
),
),
],
],
),
const SizedBox(height: Grid.half),
// Message preview.
MessagePreview(
content: item.item.displayContent,
mentionNames: mentionNames,
mentionLabels: contextualLabels,
agentMentionPubkeys: agentMentionPubkeys,
tags: item.item.tags,
maxLines: 2,
baseStyle: activityPreviewTextStyle
.copyWith(
color: context.colors.onSurface,
),
),
],
),
),
],
),
),
),
),
),
),
],
),
);
},
);
}
/// Messages, not other inbox activity, can start a Solo chat.
bool get _canStartSoloChat =>
item.item.channelId != null &&
item.item.content.trim().isNotEmpty &&
const {
EventKind.streamMessage,
EventKind.streamMessageV2,
EventKind.forumPost,
EventKind.forumComment,
}.contains(item.item.kind);
/// Thread root that Follow acts on: the conversation's root for thread
/// rows, the message itself for top-level rows (matching the message
/// actions sheet). Solo chats have no threads, and grouped DM conversations
/// have no single thread, so neither offers Follow.
String? get _followRootId {
if (channel?.isSolo ?? false) return null;
if (item.conversationId.startsWith('dm:')) return null;
return item.conversationId;
}
void _showRowActions(BuildContext context, WidgetRef ref) {
final followRootId = _followRootId;
final following =
followRootId != null &&
ref.read(threadFollowsProvider).isFollowing(followRootId);
final reminderChannelId = item.item.channelId;
final canRemind =
reminderChannelId != null && ref.read(reminderServiceProvider) != null;
showBuzzModalBottomSheet<void>(
context: context,
builder: (sheetContext) => SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.fromLTRB(
Grid.gutter,
0,
Grid.gutter,
Grid.xs,
),
child: IconTheme.merge(
data: const IconThemeData(size: 18),
child: SheetActionSection(
children: [
ListTile(
leading: Icon(isDone ? BuzzIcons.mail : BuzzIcons.mailOpen),
title: Text(isDone ? 'Mark unread' : 'Mark as read'),
onTap: () {
Navigator.of(sheetContext).pop();
isDone ? onMarkUnread() : onMarkRead();
},
),
if (followRootId != null)
ListTile(
leading: Icon(
following ? BuzzIcons.bellOff : BuzzIcons.bellRing,
),
title: Text(
following ? 'Unfollow thread' : 'Follow thread',
),
onTap: () async {
final messenger = ScaffoldMessenger.maybeOf(context);
Navigator.of(sheetContext).pop();
final notifier = ref.read(
threadFollowsProvider.notifier,
);
final channelId = item.item.channelId;
if (channelId == null) return;
final saved = await (following
? notifier.unfollowThread(channelId, followRootId)
: notifier.followThread(channelId, followRootId));
if (!saved) {
messenger?.showFeedbackSnackBar(
SnackBar(content: Text(notifier.failureMessage)),
kind: ToastKind.error,
);
}
},
),
if (canRemind)
ListTile(
leading: const Icon(BuzzIcons.clock),
title: const Text('Remind me'),
onTap: () {
Navigator.of(sheetContext).pop();
unawaited(
_remindMe(context, ref, channelId: reminderChannelId),
);
},
),
ListTile(
leading: const Icon(BuzzIcons.externalLink),
title: const Text('Open conversation'),
onTap: () {
Navigator.of(sheetContext).pop();
onTap();
},
),
if (_canStartSoloChat)
ListTile(
leading: const Icon(BuzzIcons.messageCircle),
title: const Text('Start Solo chat'),
onTap: () {
Navigator.of(sheetContext).pop();
final message = item.item;
unawaited(
openSoloChatFromMessage(
context,
ref,
channel: channel,
channelId: message.channelId!,
messageId: message.id,
threadRootId: parseThreadReference(
message.tags,
).rootId,
content: message.content,
),
);
},
),
],
),
),
),
),
),
);
}
/// Opens the reminder sheet for the row's message. An existing pending
/// reminder for that message is rescheduled rather than duplicated, so the
/// reminder list must be loaded first (it otherwise loads only with the
/// Reminders filter).
Future<void> _remindMe(
BuildContext context,
WidgetRef ref, {
required String channelId,
}) async {
final List<Reminder> reminders;
try {
reminders = await ref.read(remindersProvider.future);
} catch (error) {
debugPrint('[Inbox] loading reminders failed: $error');
if (!context.mounted) return;
ScaffoldMessenger.of(context).showFeedbackSnackBar(
const SnackBar(content: Text('Couldn’t load reminders. Try again.')),
kind: ToastKind.error,
);
return;
}
if (!context.mounted) return;
final existing = reminders
.where(
(reminder) =>
reminder.status == 'pending' &&
reminder.target?.eventId == item.item.id,
)
.firstOrNull;
showRemindMeLaterSheet(
context: context,
ref: ref,
target: ReminderTarget(
eventId: item.item.id,
channelId: channelId,
preview: item.item.displayContent.characters
.take(_inboxReminderPreviewLength)
.toString(),
authorPubkey: item.item.pubkey,
),
existing: existing == null
? null
: (dTag: existing.id, note: existing.note),
onSaved: () => unawaited(ref.read(remindersProvider.notifier).refresh()),
);
}
}
class _InboxSwipeAction extends StatelessWidget {
final Color color;
final Color foregroundColor;
final IconData icon;
final String label;
final VoidCallback onTap;
const _InboxSwipeAction({
super.key,
required this.color,
required this.foregroundColor,
required this.icon,
required this.label,
required this.onTap,
});
@override
Widget build(BuildContext context) => Material(
color: color,
borderRadius: BorderRadius.circular(Radii.full),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(Radii.full),
child: Semantics(
button: true,
label: label,
child: LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth < Grid.lg) {
return const SizedBox.shrink();
}
final showLabel =
constraints.maxWidth >= _inboxSwipeActionLabelMinWidth;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 18, color: foregroundColor),
if (showLabel) ...[
const SizedBox(height: Grid.quarter),
Padding(
padding: const EdgeInsets.symmetric(horizontal: Grid.xxs),
child: Text(
label,
maxLines: 2,
softWrap: true,
textAlign: TextAlign.center,
style: context.textTheme.labelSmall?.copyWith(
color: foregroundColor,
fontWeight: FontWeight.w600,
),
),
),
],
],
);
},
),
),
),
);
}
class _RowAvatar extends StatelessWidget {
final String pubkey;
final UserProfile? profile;
final bool isAgent;
const _RowAvatar({
required this.pubkey,
required this.profile,
required this.isAgent,
});
@override
Widget build(BuildContext context) {
final initial =
profile?.initial ?? (pubkey.isNotEmpty ? pubkey[0].toUpperCase() : '?');
return AvatarImage(
imageUrl: profile?.avatarUrl,
radius: activityAvatarSize / 2,
backgroundColor: context.controlSurface,
fallback: Text(
initial,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color: context.colors.onPrimaryContainer,
),
),
isAgent: isAgent,
);
}
}