Files
buzz/mobile/lib/features/channels/compose_bar/message_edit_sheet.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

467 lines
17 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 '../compose_bar.dart';
/// Opens the sheet that edits the text of [message] in [channelId].
///
/// The sheet offers the composer's `@` chooser with the same rules, and a
/// pick inserts the same bound chip. An edit notifies nobody: the saved
/// edit event carries the tags the edit path writes today and never a `p`
/// tag. Each chip is saved in the body as an identity link to its exact key
/// (`[@Name](nostr:npub1…)`, buzz-app's edit rule; project recommendation
/// 9), which the bubble draws as that person's pill. The message's existing
/// mentions and identity links open as chips, except a name inside code or
/// inside another Markdown link, which stays the text it was; a pick made
/// there stays text too, so no link is ever written inside a link.
void showMessageEditSheet({
required BuildContext context,
required TimelineMessage message,
required String channelId,
}) {
// One instance for the sheet's life: the route calls its builder again on
// every keyboard frame, and an identical widget is not rebuilt.
final sheet = _MessageEditSheet(message: message, channelId: channelId);
showBuzzModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
builder: (_) => sheet,
);
}
class _MessageEditSheet extends HookConsumerWidget {
final TimelineMessage message;
final String channelId;
const _MessageEditSheet({required this.message, required this.channelId});
@override
Widget build(BuildContext context, WidgetRef ref) {
final controller = useMemoized(
() => _MarkdownEditingController(portableProse: true),
);
useEffect(() => controller.dispose, [controller]);
final focusNode = useFocusNode();
final stylusHandwriting = useMemoized(
() => StylusHandwritingCutoff(controller, focusNode),
[controller, focusNode],
);
useEffect(() => stylusHandwriting.dispose, [stylusHandwriting]);
final isModifyingText = useRef(false);
final lastObservedEditingValue = useRef(controller.value);
final currentPubkey = ref.watch(currentPubkeyProvider);
final userCache = ref.watch(userCacheProvider);
final channelsAsync = ref.watch(channelsProvider);
final membersAsync = ref.watch(channelMembersProvider(channelId));
final sessionStatus = ref.watch(relaySessionProvider).status;
final cachedMembers = channelsAsync.asData == null
? const <ChannelMember>[]
: ref
.read(channelsProvider.notifier)
.cachedMembersForChannel(channelId);
final agentOwners = ref.watch(agentOwnersProvider).asData?.value;
final channel = ref.watch(channelByIdProvider(channelId));
List<MentionCandidate> memberCandidates() => _typedMemberCandidates(
membersAsync: membersAsync,
sessionStatus: sessionStatus,
cachedMembers: cachedMembers,
userCache: userCache,
agentOwners: agentOwners,
);
_useMentionChipQualifiers(
ref: ref,
controller: controller,
roster: channelMembersForAutocomplete(
membersAsync: membersAsync,
sessionStatus: sessionStatus,
cachedMembers: cachedMembers,
),
userCache: userCache,
agentOwners: agentOwners,
);
// The message's existing mentions, as the bubble names them, open as
// chips. The field is filled once. Names can arrive after the sheet (a
// profile still loading), so the chips are brought up to date only
// while the draft is still exactly what was last seeded: a field the
// user cleared or changed is never filled again.
final parsed = _editedMessageDraft(
message,
names: _editedMentionNames(
ref,
message: message,
channelId: channelId,
userCache: userCache,
members: channelMembersForAutocomplete(
membersAsync: membersAsync,
sessionStatus: sessionStatus,
cachedMembers: cachedMembers,
),
),
agentPubkeys: ref.watch(agentMentionPubkeysProvider(channelId)),
members: memberCandidates(),
code: controller._styledCodeRanges(message.content),
);
// A chip is seeded only where the bubble draws a pill and every other
// Markdown reader reads prose. A name inside code (a span or fence of
// any form, or an indented block) or a link (`[@Bob](https://…)`, a
// reference `[@Bob]` and its definition in any case) is that code's or
// link's own text: it opens as text, so saving leaves it exactly as
// written.
final seed = (
text: parsed.text,
mentions: controller._inProse(parsed.text, parsed.mentions),
);
final seeded = useRef<_EditedDraft?>(null);
_EditedDraft currentDraft() => (
text: controller.text,
bound: [for (final m in controller.mentions) (m.range, m.pubkey)],
);
final seedBound = [for (final m in seed.mentions) (m.range, m.pubkey)];
useEffect(() {
final last = seeded.value;
if (last != null &&
(!_sameEditedDraft(last, currentDraft()) ||
listEquals(last.bound, seedBound))) {
return null;
}
isModifyingText.value = true;
try {
controller.replaceDraft(
TextEditingValue(
text: seed.text,
selection: last != null && controller.selection.isValid
? controller.selection
: TextSelection.collapsed(offset: seed.text.length),
),
mentions: seed.mentions,
);
} finally {
isModifyingText.value = false;
}
seeded.value = (text: seed.text, bound: seedBound);
return null;
}, [controller, seedBound.join(',')]);
// Read after seeding, so a long message opens with handwriting already off
// and the first frame never measures it.
final stylusHandwritingEnabled = useValueListenable(stylusHandwriting);
_usePlatformUndoBindings(controller, focusNode);
final chooser = _useMentionChooser(
ref,
channelId: channelId,
controller: controller,
focusNode: focusNode,
isModifyingText: isModifyingText,
viewer: currentPubkey,
);
useEffect(() {
lastObservedEditingValue.value = controller.value;
void listener() {
final editingValue = controller.value;
final previousValue = lastObservedEditingValue.value;
lastObservedEditingValue.value = editingValue;
if (isModifyingText.value || editingValue == previousValue) return;
chooser.track(previousValue, editingValue);
}
controller.addListener(listener);
return () => controller.removeListener(listener);
}, [controller]);
// The chooser belongs to the focused field (recommendation 8).
final chooserOpen = useListenable(focusNode).hasFocus;
final rows = chooser.rows;
final suggestions = chooserOpen ? rows.rows : const <MentionCandidate>[];
final searchFailed = chooserOpen && rows.searchFailed;
final pickerVisible = suggestions.isNotEmpty || searchFailed;
final topMention = suggestions
.where((s) => !rows.unavailable.contains(s.pubkey))
.firstOrNull;
final pickerQuery = (chooser.query, null);
KeyEventResult handleHardwareKey(FocusNode _, KeyEvent event) =>
_handleComposerHardwareKey(
event,
controller,
inputOwned: false,
query: (chooser.liveQuery.value, null),
renderedQuery: pickerQuery,
pickerVisible: pickerVisible,
acceptSuggestion: topMention != null
? () => _runComposerAction(() => chooser.insert(topMention))
: null,
send: null,
);
void save() {
final draft = controller.text;
final text = _editedMentionContent(
draft,
controller.mentions,
code: controller._styledCodeRanges(draft),
).trim();
final unchanged =
seeded.value != null &&
_sameEditedDraft(seeded.value!, currentDraft());
if (text.isEmpty || unchanged || text == message.content) {
Navigator.of(context).pop();
return;
}
// The edit keeps the tags this path always wrote and adds no
// recipient: every chip is in the body as an identity link.
ref
.read(channelActionsProvider)
.editMessage(
channelId: channelId,
eventId: message.id,
content: text,
mediaTags: buildCustomEmojiTags(
text,
ref.read(customEmojiListProvider),
),
);
Navigator.of(context).pop();
}
return _KeyboardInset(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (pickerVisible)
Padding(
padding: const EdgeInsets.only(bottom: Grid.xxs),
child: _composerSuggestionPanel(
channelSuggestions: const [],
mentionSuggestions: suggestions,
unavailableMentions: rows.unavailable,
mentionSearchFailed: searchFailed,
reserveMentionHeight: rows.reserveHeight,
mentionSearching: rows.searching,
onMentionSearchRetry: () {
if (chooser.query case final query?) {
ref.invalidate(mentionUserSearchProvider(query));
}
},
userCache: userCache,
currentPubkey: currentPubkey,
isDmChannel: channel?.isDm ?? false,
onChannelSelect: (_) {},
onMentionSelect: chooser.insert,
),
),
Actions(
actions: {
UndoTextIntent: _ComposerHistoryAction<UndoTextIntent>(
controller,
),
RedoTextIntent: _ComposerHistoryAction<RedoTextIntent>(
controller,
),
},
child: Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: handleHardwareKey,
child: TextField(
key: const ValueKey('message-edit-field'),
controller: controller,
focusNode: focusNode,
autofocus: true,
minLines: 1,
maxLines: 5,
stylusHandwritingEnabled: stylusHandwritingEnabled,
inputFormatters: [_ComposerChipEditingFormatter(controller)],
decoration: const InputDecoration(hintText: 'Edit message'),
),
),
),
const SizedBox(height: Grid.xxs),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
const SizedBox(width: Grid.half),
FilledButton(onPressed: save, child: const Text('Save')),
],
),
],
),
),
);
}
}
/// Names for the people [message] mentions, as the bubble resolves them: the
/// cached profile, the roster's display name, the agent directory, then an
/// agent's fallback label.
Map<String, String> _editedMentionNames(
WidgetRef ref, {
required TimelineMessage message,
required String channelId,
required Map<String, UserProfile> userCache,
required List<ChannelMember> members,
}) {
final profileNames = <String, String>{};
for (final pubkey in message.mentionPubkeys) {
final key = pubkey.toLowerCase();
final name =
userCache[key]?.displayName ??
members
.where((m) => m.pubkey.toLowerCase() == key)
.firstOrNull
?.displayName;
if (name != null && name.trim().isNotEmpty) profileNames[key] = name;
}
final agentPubkeys = ref.watch(agentMentionPubkeysProvider(channelId));
return mentionNamesWithDirectoryLabels(
mentionPubkeys: message.mentionPubkeys,
profileMentionNames: profileNames,
directoryDisplayNames: ref.watch(agentDirectoryDisplayNamesProvider),
agentMentionPubkeys: {
for (final pubkey in message.mentionPubkeys)
if (agentPubkeys.contains(pubkey.toLowerCase())) pubkey.toLowerCase(),
},
);
}
/// Keeps its [child] above the keyboard. The inset changes on every frame
/// of the keyboard's animation; reading it here rebuilds this padding alone,
/// not the sheet and the roster's mention candidates it builds.
class _KeyboardInset extends StatelessWidget {
final Widget child;
const _KeyboardInset({required this.child});
@override
Widget build(BuildContext context) => Padding(
padding: EdgeInsets.fromLTRB(
Grid.gutter,
0,
Grid.gutter,
MediaQuery.viewInsetsOf(context).bottom,
),
child: child,
);
}
/// An edit draft's text and the key bound at each chip's range.
typedef _EditedDraft = ({String text, List<(MentionRange, String)> bound});
bool _sameEditedDraft(_EditedDraft a, _EditedDraft b) =>
a.text == b.text && listEquals(a.bound, b.bound);
final _keyQualifier = RegExp(r' \(([0-9a-f]{64})\)$', caseSensitive: false);
/// The body an edit saves for [text]: each chip becomes an identity link to
/// its exact key, a display-only reference that notifies nobody and that
/// every reader resolves without a tag. Two picked namesakes are two links
/// with the same label, so no key is written as prose. A chip inside [code]
/// the composer styles stays as typed.
String _editedMentionContent(
String text,
List<_ComposerMention> mentions, {
required List<TextRange> code,
}) {
var content = text;
for (final mention in mentions.reversed) {
if (code.any((c) => c.start < mention.start && mention.end < c.end)) {
continue;
}
// A chip seeded from `@Name (<key>)` names its key in the link instead.
var label = text.substring(mention.start, mention.end);
if (_keyQualifier.firstMatch(label)?[1]?.toLowerCase() == mention.pubkey) {
label = label.replaceFirst(_keyQualifier, '');
}
content = content.replaceRange(
mention.start,
mention.end,
mentionIdentityLink(label, mention.pubkey),
);
}
return content;
}
/// The draft that edits [message]: its text, with each identity link the
/// bubble draws as a pill (outside [code] and all other code and links)
/// shown as its `@Name`, and its chips in text order. A chip is an
/// identity link, bound to the key it names, or an `@Name` or
/// `@Name (<key>)` the content writes for exactly one tagged person; a name
/// two tagged people share stays text, since the text cannot say which one
/// it meant.
({String text, List<_ComposerMention> mentions}) _editedMessageDraft(
TimelineMessage message, {
required Map<String, String> names,
required Set<String> agentPubkeys,
required List<MentionCandidate> members,
required List<TextRange> code,
}) {
_ComposerMention chip(int start, int end, String pubkey, String? name) =>
_ComposerMention(
start: start,
end: end,
candidate:
members
.where((m) => m.pubkey.toLowerCase() == pubkey)
.firstOrNull ??
MentionCandidate(
pubkey: pubkey,
displayName: name,
isAgent: agentPubkeys.contains(pubkey),
),
);
final text = StringBuffer();
final mentions = <_ComposerMention>[];
var offset = 0;
final links = mentionIdentityLinks(message.content).toList();
// An identity link the bubble shows as raw text (inside code of any kind)
// or inside another link stays as written.
final literal = mentionsInsideMarkdownLinks(
message.content,
[for (final link in links) (start: link.start, end: link.end)],
keep: 0,
portable: true,
);
for (final (i, link) in links.indexed) {
if (literal.contains(i) ||
code.any((c) => c.start < link.start && link.end < c.end)) {
continue;
}
text.write(message.content.substring(offset, link.start));
final start = text.length;
text.write(link.label);
mentions.add(
chip(start, text.length, link.pubkey, link.label.substring(1)),
);
offset = link.end;
}
text.write(message.content.substring(offset));
final draft = text.toString();
final keysByLabel = <String, Set<String>>{};
for (final MapEntry(key: pubkey, value: name) in names.entries) {
// Folded as the scan compares names, so `Sam` and `ſam` share one entry
// and an ambiguous historical label binds no key.
(keysByLabel[foldMentionLabel(name)] ??= {}).add(pubkey);
keysByLabel[foldMentionLabel('$name ($pubkey)')] = {pubkey};
}
final linked = [...mentions];
for (final range in mentionOccurrences(draft, keysByLabel.keys)) {
if (linked.any((m) => m.start < range.end && range.start < m.end)) continue;
if (keysByLabel[foldMentionLabel(range.label)] case final keys?
when keys.length == 1) {
mentions.add(
chip(range.start, range.end, keys.single, names[keys.single]),
);
}
}
return (
text: draft,
mentions: mentions..sort((a, b) => a.start.compareTo(b.start)),
);
}