Skip to content

Commit b3b1256

Browse files
committed
fix(mobile): bind same-name mentions to exact selected identities
Two members sharing a display name could not be told apart in mobile mentions: picking the second overwrote the first's selection, rendering linked whichever same-name person matched first, and a later rename or a shorter name could re-bind the text to the wrong recipient. This binds every mention to the exact selected identity: - Track each same-name selection under its recipient key instead of overwriting by label; conflicting picks render a qualified label like `Name (key...)`. - Match the longest label first, so a shorter or interior name can never claim part of a longer one and steal its identity; ambiguous labels block shorter mentions instead of silently re-binding. - Render mentions from the signed identity key in each event's tags, never from message text alone, so qualified labels stay correct regardless of tag order and survive later renames. Qualified-label authority now derives from the event's complete signed tags (`p` and reference-only `mention` entries), computed inside MessageContent and passed explicitly to the binding computation, never from optional cached display names: a signed full-key mention keeps its exact navigation even when its profile is missing, while ordinary aliases and untagged namesakes stay denied. Sorted signed keys join the rendered presentation identity so a rebuilt body cannot retain stale authorization. - Persist exact identity selections with the draft text; malformed records refuse visibly, and send revalidates saved mentions instead of falling back to a same-name roster entry. Qualified-label destinations are asserted through the production ChannelDetailPage and ThreadDetailPage consumers across both signed tag orders and present, renamed, key-fallback and missing profiles, tapping each qualified label to open exactly its signed profile sheet. Ports the landed Desktop exact-recipient behavior (docs/mention-editor.md). Full mobile package suite passes on this tree (2,121 tests), with the analyzer and formatter clean. Signed-off-by: Logan Johnson <[email protected]>
1 parent 092c6a7 commit b3b1256

14 files changed

Lines changed: 837 additions & 61 deletions

‎mobile/lib/features/activity/compose_drafts_provider.dart‎

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ class ComposeDraft {
2222
final String channelId;
2323
final String? threadHeadId;
2424
final String text;
25+
26+
/// Literal picker labels bound to exact keys, never authorization metadata.
27+
/// An empty key/value is a malformed-record tombstone; send must refuse it.
28+
final Map<String, String> mentionKeys;
2529
final int updatedAt; // unix seconds
2630

2731
const ComposeDraft({
@@ -30,13 +34,15 @@ class ComposeDraft {
3034
required this.threadHeadId,
3135
required this.text,
3236
required this.updatedAt,
37+
this.mentionKeys = const {},
3338
});
3439

3540
Map<String, dynamic> toJson() => {
3641
'key': key,
3742
'channel_id': channelId,
3843
if (threadHeadId != null) 'thread_head_id': threadHeadId,
3944
'text': text,
45+
'mention_keys': mentionKeys,
4046
'updated_at': updatedAt,
4147
};
4248

@@ -48,10 +54,32 @@ class ComposeDraft {
4854
final updatedAt = raw['updated_at'];
4955
if (key is! String || channelId is! String || text is! String) return null;
5056
if (text.trim().isEmpty) return null;
57+
final bindings = raw['mention_keys'];
58+
final mentionKeys = <String, String>{};
59+
if (raw.containsKey('mention_keys')) {
60+
if (bindings is! Map<String, dynamic>) {
61+
mentionKeys[''] = '';
62+
} else {
63+
final labels = <String>{};
64+
for (final entry in bindings.entries) {
65+
if (!labels.add(entry.key.toLowerCase())) mentionKeys[''] = '';
66+
final value = entry.value;
67+
mentionKeys[entry.key] =
68+
entry.key.isNotEmpty &&
69+
value is String &&
70+
RegExp(r'^[0-9a-fA-F]{64}$').hasMatch(value)
71+
? value.toLowerCase()
72+
: '';
73+
}
74+
}
75+
}
5176
return ComposeDraft(
5277
key: key,
5378
channelId: channelId,
54-
threadHeadId: raw['thread_head_id'] as String?,
79+
threadHeadId: raw['thread_head_id'] is String
80+
? raw['thread_head_id'] as String
81+
: null,
82+
mentionKeys: Map.unmodifiable(mentionKeys),
5583
text: text,
5684
updatedAt: updatedAt is int ? updatedAt : 0,
5785
);
@@ -108,18 +136,23 @@ class ComposeDraftsNotifier extends Notifier<List<ComposeDraft>> {
108136
required String channelId,
109137
String? threadHeadId,
110138
required String text,
139+
Map<String, String> mentionKeys = const {},
111140
}) {
112141
if (text.trim().isEmpty) {
113142
remove(key);
114143
return;
115144
}
116145
final existing = state.where((d) => d.key == key).firstOrNull;
117-
if (existing?.text == text) return;
146+
if (existing?.text == text &&
147+
mapEquals(existing?.mentionKeys, mentionKeys)) {
148+
return;
149+
}
118150
final draft = ComposeDraft(
119151
key: key,
120152
channelId: channelId,
121153
threadHeadId: threadHeadId,
122154
text: text,
155+
mentionKeys: Map.unmodifiable(mentionKeys),
123156
updatedAt: DateTime.now().millisecondsSinceEpoch ~/ 1000,
124157
);
125158
final next = [draft, ...state.where((d) => d.key != key)];
@@ -131,8 +164,11 @@ class ComposeDraftsNotifier extends Notifier<List<ComposeDraft>> {
131164
_persist([...state.where((d) => d.key != key)]);
132165
}
133166

134-
String? textFor(String key) =>
135-
state.where((d) => d.key == key).firstOrNull?.text;
167+
/// Read text and selected identities from the same persisted snapshot.
168+
ComposeDraft? draftFor(String key) =>
169+
state.where((d) => d.key == key).firstOrNull;
170+
171+
String? textFor(String key) => draftFor(key)?.text;
136172

137173
void _persist(List<ComposeDraft> drafts) {
138174
state = List.unmodifiable(drafts);

‎mobile/lib/features/channels/compose_bar.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';
1818
import 'package:nostr/nostr.dart' as nostr;
1919

2020
import '../../shared/mentions/agent_identity_provider.dart';
21+
import '../../shared/mentions/mention_bindings.dart';
2122
import '../../shared/huddle/huddle_session.dart';
2223
import '../../shared/relay/relay.dart';
2324
import '../../shared/theme/theme.dart';
Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,54 @@
11
part of '../compose_bar.dart';
22

33
Set<String> _agentMentionLabels({
4-
required Iterable<MentionCandidate> candidates,
5-
}) {
6-
return <String>{
7-
for (final candidate in candidates)
8-
if (candidate.isAgent) candidate.label,
4+
required Map<String, MentionCandidate> bindings,
5+
}) => {
6+
for (final entry in bindings.entries)
7+
if (entry.value.isAgent) entry.key,
8+
};
9+
10+
List<MentionCandidate> _resolveComposerMentions(
11+
String text,
12+
Map<String, MentionCandidate> selected,
13+
List<MentionCandidate> members,
14+
List<MentionCandidate> restoredCandidates,
15+
) {
16+
// A broken record cannot fall back to a same-name roster entry.
17+
if (selected.values.any((c) => c.pubkey.isEmpty)) {
18+
throw const FormatException(
19+
'Saved mention identity is invalid. Clear the draft and select again.',
20+
);
21+
}
22+
final candidates = <String, List<MentionCandidate>>{
23+
for (final e in selected.entries) e.key.toLowerCase(): [e.value],
924
};
25+
final selectedNames = candidates.keys.toSet();
26+
for (final member in members) {
27+
final label = member.label.toLowerCase();
28+
if (!selectedNames.contains(label)) (candidates[label] ??= []).add(member);
29+
}
30+
final winners = <String, MentionCandidate>{};
31+
for (final range in mentionOccurrences(text, candidates.keys)) {
32+
final identities = {
33+
for (final c in candidates[range.label]!) c.pubkey.toLowerCase(): c,
34+
};
35+
if (identities.length > 1) {
36+
throw FormatException(
37+
'The mention @${range.label} is ambiguous. Choose a recipient from the mention picker.',
38+
);
39+
}
40+
for (final entry in identities.entries) {
41+
final selected = entry.value;
42+
final current = restoredCandidates
43+
.where((c) => c.pubkey == entry.key)
44+
.firstOrNull;
45+
if (selected.requiresRevalidation && current == null) {
46+
throw const FormatException(
47+
'Saved mention is no longer available. Select it again from the picker.',
48+
);
49+
}
50+
winners[entry.key] = selected.requiresRevalidation ? current! : selected;
51+
}
52+
}
53+
return winners.values.toList();
1054
}

‎mobile/lib/features/channels/compose_bar/compose_bar_widget.dart‎

Lines changed: 52 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,9 @@ class ComposeBar extends HookConsumerWidget {
8686
attachments: attachments,
8787
);
8888
final voiceNoteRef = useRef(voiceNote)..value = voiceNote;
89+
final mentionMap = useRef(<String, MentionCandidate>{});
8990
_useComposeDraftLifecycle(
91+
mentionMap: mentionMap,
9092
ref: ref,
9193
controller: controller,
9294
draftKey: draftKey,
@@ -219,7 +221,6 @@ class ComposeBar extends HookConsumerWidget {
219221
// Map of displayName → selected mention candidate built as the user selects
220222
// mentions. Used to pass resolved pubkeys directly to onSend and to attach
221223
// selected non-member agents before the message is published.
222-
final mentionMap = useRef(<String, MentionCandidate>{});
223224

224225
// Channel autocomplete state ----------------------------------------------
225226
final channelQuery = useState<String?>(null);
@@ -244,9 +245,7 @@ class ComposeBar extends HookConsumerWidget {
244245
// owners so @mention suggestions show names ("managed by …" included).
245246
final relayAgents = ref.watch(agentDirectoryProvider).asData?.value;
246247
final agentOwners = ref.watch(agentOwnersProvider).asData?.value;
247-
final agentMentionLabels = _agentMentionLabels(
248-
candidates: mentionMap.value.values,
249-
);
248+
final agentMentionLabels = _agentMentionLabels(bindings: mentionMap.value);
250249
final agentMentionLabelsKey = (agentMentionLabels.toList()..sort()).join(
251250
'\u0000',
252251
);
@@ -263,6 +262,9 @@ class ComposeBar extends HookConsumerWidget {
263262
);
264263
final pubkeys = [
265264
...memberList.map((m) => m.pubkey),
265+
...mentionMap.value.values
266+
.where((c) => c.requiresRevalidation && c.pubkey.isNotEmpty)
267+
.map((c) => c.pubkey),
266268
...?relayAgents?.map((a) => a.pubkey),
267269
...?agentOwners?.values,
268270
];
@@ -272,6 +274,8 @@ class ComposeBar extends HookConsumerWidget {
272274
return null;
273275
},
274276
[
277+
draftIdentity,
278+
draftKey,
275279
membersAsync.asData?.value.length,
276280
cachedMembers.length,
277281
relayAgents?.length,
@@ -382,7 +386,10 @@ class ComposeBar extends HookConsumerWidget {
382386

383387
// Insert a selected mention into the text field.
384388
void insertMention(MentionCandidate candidate) {
385-
final name = candidate.label;
389+
final name = selectedMentionLabel(candidate.label, candidate.pubkey, {
390+
for (final entry in mentionMap.value.entries)
391+
entry.key: entry.value.pubkey,
392+
});
386393
// Track the resolved candidate so we can pass its pubkey and prepare
387394
// selected non-member agents at send time.
388395
mentionMap.value[name] = candidate;
@@ -470,10 +477,45 @@ class ComposeBar extends HookConsumerWidget {
470477
final messenger = ScaffoldMessenger.maybeOf(context);
471478

472479
// Extract pubkeys for mentions present in the final text.
473-
final selectedMentions = <MentionCandidate>[
474-
for (final entry in mentionMap.value.entries)
475-
if (hasMention(text, entry.key)) entry.value,
476-
];
480+
List<MentionCandidate> selectedMentions;
481+
try {
482+
selectedMentions = _resolveComposerMentions(
483+
text,
484+
mentionMap.value,
485+
buildMentionCandidates(
486+
members: channelMembersForAutocomplete(
487+
membersAsync: membersAsync,
488+
sessionStatus: sessionStatus,
489+
cachedMembers: cachedMembers,
490+
),
491+
relayAgents: const [],
492+
sharedChannelIds: const {},
493+
userCache: userCache,
494+
ownerByAgentPubkey: agentOwners ?? const {},
495+
),
496+
buildMentionCandidates(
497+
members: membersAsync.asData?.value ?? const [],
498+
relayAgents: relayAgents ?? const [],
499+
sharedChannelIds: {
500+
for (final c in channels)
501+
if (c.isMember && !c.isArchived) c.id,
502+
},
503+
userCache: userCache,
504+
ownerByAgentPubkey: agentOwners ?? const {},
505+
currentPubkey: currentPubkey,
506+
// Reuse ordinary search-result classification, not membership as
507+
// permission. Persisted keys/flags themselves prove no role.
508+
searchResults: [
509+
for (final c in mentionMap.value.values)
510+
if (c.requiresRevalidation && userCache[c.pubkey] != null)
511+
userCache[c.pubkey]!,
512+
],
513+
),
514+
);
515+
} on FormatException catch (error) {
516+
messenger?.showSnackBar(SnackBar(content: Text(error.message)));
517+
return;
518+
}
477519
final outgoing = _OutgoingMentions(selectedMentions);
478520
final scan = await _scanNonMemberMentions(
479521
ref,
@@ -589,12 +631,12 @@ class ComposeBar extends HookConsumerWidget {
589631
if (context.mounted &&
590632
queueGeneration == uploadGeneration.value &&
591633
draftRevision.value == clearedDraftRevision) {
592-
controller.value = draftText;
593634
attachments.value = draftAttachments;
594635
retainedForRetry = true;
595636
mentionMap.value
596637
..clear()
597638
..addAll(draftMentions);
639+
controller.value = draftText;
598640
focusNode.requestFocus();
599641
}
600642
} finally {

‎mobile/lib/features/channels/compose_bar/draft_lifecycle.dart‎

Lines changed: 47 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@ Future<void> _sendTextOnlyDraft({
2626
draftRevision.value != clearedDraftRevision) {
2727
return;
2828
}
29-
controller.value = clearedDraftText;
3029
mentionMap.value
3130
..clear()
3231
..addAll(clearedDraftMentions);
32+
controller.value = clearedDraftText;
3333
focusNode.requestFocus();
3434
}
3535

@@ -63,6 +63,7 @@ Future<void> _sendTextOnlyDraft({
6363
}
6464

6565
void _useComposeDraftLifecycle({
66+
required ObjectRef<Map<String, MentionCandidate>> mentionMap,
6667
required WidgetRef ref,
6768
required _MarkdownEditingController controller,
6869
required String draftKey,
@@ -82,11 +83,25 @@ void _useComposeDraftLifecycle({
8283
}) {
8384
final lastDraftIdentity = useRef<String?>(null);
8485
useEffect(() {
86+
final identity = '$draftIdentity\u0000$draftKey';
87+
final shouldHydrate = lastDraftIdentity.value != identity;
8588
final identityChanged =
86-
lastDraftIdentity.value != null &&
87-
lastDraftIdentity.value != draftIdentity;
88-
lastDraftIdentity.value = draftIdentity;
89-
final saved = ref.read(composeDraftsProvider.notifier).textFor(draftKey);
89+
lastDraftIdentity.value != null && lastDraftIdentity.value != identity;
90+
lastDraftIdentity.value = identity;
91+
final saved = ref.read(composeDraftsProvider.notifier).draftFor(draftKey);
92+
if (shouldHydrate) {
93+
mentionMap.value
94+
..clear()
95+
..addAll({
96+
for (final entry
97+
in (saved?.mentionKeys ?? <String, String>{}).entries)
98+
entry.key: MentionCandidate(
99+
pubkey: entry.value,
100+
displayName: entry.key,
101+
requiresRevalidation: true,
102+
),
103+
});
104+
}
90105
if (identityChanged) {
91106
draftRevision.value += 1;
92107
onDraftIdentityChanged();
@@ -101,15 +116,38 @@ void _useComposeDraftLifecycle({
101116
final staleAttachments = attachments.value;
102117
attachments.value = const [];
103118
unawaited(_deleteOwnedAttachments(staleAttachments));
104-
controller.text = saved ?? '';
119+
controller.text = saved?.text ?? '';
105120
} else if (saved != null && controller.text.isEmpty) {
106-
controller.text = saved;
121+
controller.text = saved.text;
107122
}
108123

109124
var lastPersistedText = controller.text;
125+
var lastBindings = <String, String>{
126+
for (final e in mentionMap.value.entries) e.key: e.value.pubkey,
127+
};
110128
void persistDraft() {
111129
final text = controller.text;
112-
if (text == lastPersistedText) return;
130+
if (text != lastPersistedText) {
131+
// Prune before the atomic snapshot, not in a later editor listener.
132+
// Code formatting hides a binding without deleting its literal.
133+
final retained = mentionOccurrences(
134+
text.replaceAll('`', ' '),
135+
mentionMap.value.keys,
136+
).map((range) => range.label).toSet();
137+
// Whole-record taint has no literal to prune. Removing every @ is a
138+
// safe reset; unrelated edits must not turn lost keys into name lookup.
139+
mentionMap.value.removeWhere(
140+
(label, _) =>
141+
label.isEmpty ? !text.contains('@') : !retained.contains(label),
142+
);
143+
}
144+
final bindings = <String, String>{
145+
for (final e in mentionMap.value.entries) e.key: e.value.pubkey,
146+
};
147+
if (text == lastPersistedText && mapEquals(bindings, lastBindings)) {
148+
return;
149+
}
150+
lastBindings = bindings;
113151
lastPersistedText = text;
114152
draftRevision.value += 1;
115153
ref
@@ -119,6 +157,7 @@ void _useComposeDraftLifecycle({
119157
channelId: channelId,
120158
threadHeadId: threadHeadId,
121159
text: text,
160+
mentionKeys: bindings,
122161
);
123162
}
124163

0 commit comments

Comments
 (0)