Skip to content

Commit 7615656

Browse files
committed
fix: resolve multi-word display names in @mention pipeline
The CLI mention resolver stopped at the first space when scanning for @NAMEs, so '@will Pfleger' only extracted 'will' — which never matched the profile display_name 'Will Pfleger'. Result: no p-tag, no notification. **Root cause (sprout-sdk/mentions.rs)** extract_at_names() tokenizes on alphanumeric+._- chars only, so it can never produce a multi-word token. match_names_to_profiles() then does a full-string equality check against the profile display_name, so a single-word extract like 'will' never matches 'Will Pfleger'. **Fix 1 — new two-pass extractor (sprout-sdk/mentions.rs)** Add extract_at_mentions_with_known(content, known_names): - Sort known_names longest-first (so 'Will Pfleger' beats 'Will') - At each @ token, try each known name case-insensitively with a word-boundary check (whitespace / punctuation / EOS) - Fall back to the existing single-word tokenizer for unmatched @ tokens so @alice still works even when profiles are loading - Deduplicate, preserve first-seen order **Fix 2 — wire it into the CLI (sprout-cli/messages.rs)** resolve_content_mentions() now extracts display_names from the fetched profiles first, passes them into extract_at_mentions_with_known, then maps matched names back to pubkeys via match_names_to_profiles. The early-exit guard is also tightened to skip I/O when content has no '@'. **Fix 3 — remove false-positive mention rendering (desktop)** buildPrefixPattern() previously fell back to prefix+\S+ when no known names were available, causing '@will' to render as a blue mention even though no user named 'Will' exists. Changed the empty-names branch to return a never-matching regex (/(?!)/gi) so only text backed by an actual p-tagged member gets mention styling.
1 parent d8278f7 commit 7615656

3 files changed

Lines changed: 271 additions & 12 deletions

File tree

‎crates/sprout-cli/src/commands/messages.rs‎

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ use crate::validate::{
88
infer_language, parse_event_id, parse_uuid, read_or_stdin, truncate_diff,
99
validate_content_size, validate_hex64, validate_uuid, MAX_DIFF_BYTES,
1010
};
11-
use sprout_sdk::mentions::{extract_at_names, match_names_to_profiles, MentionProfile};
11+
use sprout_sdk::mentions::{
12+
extract_at_mentions_with_known, match_names_to_profiles, MentionProfile,
13+
};
1214

1315
// ---------------------------------------------------------------------------
1416
// Helpers
@@ -124,18 +126,24 @@ async fn resolve_channel_id(client: &SproutClient, event_id: &str) -> Result<Uui
124126
///
125127
/// Mirrors the MCP implementation: queries kind 39002 (channel members),
126128
/// then kind 0 (profiles for those members), and delegates parsing and
127-
/// case-insensitive matching to [`sprout_sdk::mentions`]. On any I/O or
128-
/// parse failure, returns an empty vec — auto-tagging is best-effort and
129-
/// must never block a send.
129+
/// case-insensitive matching to [`sprout_sdk::mentions`].
130+
///
131+
/// Uses [`extract_at_mentions_with_known`] so that multi-word display names
132+
/// (e.g. "Will Pfleger") are matched correctly — the known member names are
133+
/// extracted from profiles first and passed into the two-pass extractor.
134+
///
135+
/// On any I/O or parse failure, returns an empty vec — auto-tagging is
136+
/// best-effort and must never block a send.
130137
async fn resolve_content_mentions(
131138
client: &SproutClient,
132139
channel_id: &str,
133140
content: &str,
134141
) -> Vec<String> {
135-
let names = extract_at_names(content);
136-
if names.is_empty() {
142+
// Quick pre-check: if there's no '@' at all we can skip all I/O.
143+
if !content.contains('@') {
137144
return vec![];
138145
}
146+
139147
// 1. Membership list (kind 39002 is parameterized-replaceable, addressed by `d` tag).
140148
let members_filter = serde_json::json!({
141149
"kinds": [39002],
@@ -158,7 +166,7 @@ async fn resolve_content_mentions(
158166
None => return vec![],
159167
};
160168

161-
// 3. Hand the parsed profile content + pubkey to the shared matcher.
169+
// 3. Build profile entries and extract display names for the two-pass extractor.
162170
let entries: Vec<MentionProfile<'_>> = profile_events
163171
.iter()
164172
.filter_map(|e| {
@@ -170,6 +178,30 @@ async fn resolve_content_mentions(
170178
})
171179
})
172180
.collect();
181+
182+
// Extract the display names (with `name` fallback) from each profile so
183+
// the two-pass extractor can match multi-word names like "Will Pfleger".
184+
let display_names: Vec<String> = entries
185+
.iter()
186+
.filter_map(|e| {
187+
let v: serde_json::Value = serde_json::from_str(e.content_json).ok()?;
188+
let name = v
189+
.get("display_name")
190+
.or_else(|| v.get("name"))
191+
.and_then(|n| n.as_str())
192+
.filter(|n| !n.is_empty())?;
193+
Some(name.to_string())
194+
})
195+
.collect();
196+
197+
// 4. Two-pass extraction: known multi-word names first, single-word fallback.
198+
let known_refs: Vec<&str> = display_names.iter().map(|s| s.as_str()).collect();
199+
let names = extract_at_mentions_with_known(content, &known_refs);
200+
if names.is_empty() {
201+
return vec![];
202+
}
203+
204+
// 5. Map matched names back to pubkeys via the shared profile matcher.
173205
match_names_to_profiles(&names, &entries)
174206
}
175207

‎crates/sprout-sdk/src/mentions.rs‎

Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,18 @@
1616
//! explicit mentions ──► normalize ──► merge_mentions ──► p-tags
1717
//! ```
1818
//!
19+
//! For callers that have the set of known member display names available
20+
//! upfront, [`extract_at_mentions_with_known`] provides a two-pass approach
21+
//! that correctly handles multi-word display names (e.g. "Will Pfleger"):
22+
//!
23+
//! ```text
24+
//! body text + known_names ──► extract_at_mentions_with_known ──► names: Vec<String>
25+
//! │
26+
//! direct name→pubkey lookup
27+
//! │
28+
//! p-tags (merged)
29+
//! ```
30+
//!
1931
//! See [`crate::mentions::MENTION_CAP`] for the hard upper bound on tags.
2032
2133
use std::collections::HashSet;
@@ -84,6 +96,123 @@ pub fn extract_at_names(content: &str) -> Vec<String> {
8496
names
8597
}
8698

99+
/// Extract `@mention` names from message content when the set of known member
100+
/// display names is available upfront.
101+
///
102+
/// Uses a two-pass approach to correctly handle multi-word display names
103+
/// (e.g. "Will Pfleger"):
104+
///
105+
/// **Pass 1 — known-name matching:** At each `@` token (preceded by
106+
/// start-of-string or ASCII whitespace), try each known name longest-first,
107+
/// case-insensitively. A match is accepted only when the name is followed by a
108+
/// word boundary (whitespace, common punctuation, or end-of-string). When a
109+
/// known name matches, the lowercased name is emitted and the scan advances
110+
/// past the entire matched name.
111+
///
112+
/// **Pass 2 — single-word fallback:** If no known name matches at a given `@`,
113+
/// falls back to the existing single-word tokenizer (alphanumeric + `.` `-`
114+
/// `_`) so that `@alice` still works even when Alice's profile hasn't been
115+
/// fetched yet.
116+
///
117+
/// `known_names` should be the display names (or `name` fallbacks) of all
118+
/// channel members. Duplicates and empty strings are ignored. The function
119+
/// does **not** require `known_names` to be pre-sorted — it sorts
120+
/// longest-first internally.
121+
///
122+
/// Returns lowercased names in first-seen order, deduplicated.
123+
pub fn extract_at_mentions_with_known(content: &str, known_names: &[&str]) -> Vec<String> {
124+
if content.is_empty() || !content.contains('@') {
125+
return vec![];
126+
}
127+
128+
// Sort known names longest-first so multi-word names beat their prefixes.
129+
let mut sorted_known: Vec<&str> = known_names
130+
.iter()
131+
.copied()
132+
.filter(|n| !n.trim().is_empty())
133+
.collect();
134+
sorted_known.sort_by(|a, b| b.len().cmp(&a.len()));
135+
136+
let mut names: Vec<String> = Vec::new();
137+
let mut seen = HashSet::new();
138+
let chars: Vec<char> = content.chars().collect();
139+
let len = chars.len();
140+
let mut i = 0;
141+
142+
while i < len {
143+
if chars[i] == '@' {
144+
let preceded_by_ws = i == 0 || chars[i - 1].is_ascii_whitespace();
145+
if preceded_by_ws && i + 1 < len {
146+
// Build the remaining content after '@' as a &str for prefix matching.
147+
let after_at: String = chars[i + 1..].iter().collect();
148+
149+
// Pass 1: try each known name (longest-first).
150+
let mut matched: Option<(String, usize)> = None;
151+
for known in &sorted_known {
152+
if after_at.len() < known.len() {
153+
continue;
154+
}
155+
let candidate = &after_at[..known.len()];
156+
if !candidate.eq_ignore_ascii_case(known) {
157+
continue;
158+
}
159+
// Word-boundary check: must be followed by whitespace,
160+
// common punctuation, or end-of-string.
161+
let after_name = &after_at[known.len()..];
162+
let boundary = after_name.is_empty()
163+
|| after_name
164+
.chars()
165+
.next()
166+
.map(|c| {
167+
c.is_ascii_whitespace()
168+
|| matches!(
169+
c,
170+
',' | ';' | '.' | '!' | '?' | ':' | ')' | ']' | '}'
171+
)
172+
})
173+
.unwrap_or(true);
174+
if boundary {
175+
// Advance i past '@' + matched name length (in chars).
176+
let name_char_len = known.chars().count();
177+
matched = Some((known.to_ascii_lowercase(), name_char_len));
178+
break;
179+
}
180+
}
181+
182+
if let Some((lower, char_len)) = matched {
183+
if seen.insert(lower.clone()) {
184+
names.push(lower);
185+
}
186+
// Skip past '@' + the matched name chars.
187+
i += 1 + char_len;
188+
continue;
189+
}
190+
191+
// Pass 2: single-word fallback (alphanumeric + . - _).
192+
let start = i + 1;
193+
let mut end = start;
194+
while end < len {
195+
let c = chars[end];
196+
if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' {
197+
end += 1;
198+
} else {
199+
break;
200+
}
201+
}
202+
if end > start {
203+
let name: String = chars[start..end].iter().collect();
204+
let lower = name.to_ascii_lowercase();
205+
if seen.insert(lower.clone()) {
206+
names.push(lower);
207+
}
208+
}
209+
}
210+
}
211+
i += 1;
212+
}
213+
names
214+
}
215+
87216
/// Match extracted `@names` against channel-member profiles.
88217
///
89218
/// For each profile, parses its `content_json` and reads the
@@ -205,6 +334,98 @@ mod tests {
205334
assert!(extract_at_names("hello @").is_empty());
206335
}
207336

337+
// ── extract_at_mentions_with_known ──────────────────────────────────
338+
339+
#[test]
340+
fn known_multiword_name_matches_fully() {
341+
// "Will Pfleger" should match @Will Pfleger, not just @Will.
342+
let result = extract_at_mentions_with_known("hello @Will Pfleger!", &["Will Pfleger"]);
343+
assert_eq!(result, vec!["will pfleger"]);
344+
}
345+
346+
#[test]
347+
fn partial_first_word_does_not_match_multiword_name() {
348+
// @Will alone must NOT match "Will Pfleger" — partial matches are rejected.
349+
let result = extract_at_mentions_with_known("hey @Will how are you", &["Will Pfleger"]);
350+
// No known name matches @Will (boundary check: 'Will' is followed by ' h'
351+
// which would match "Will Pfleger" only if the full name follows).
352+
// Falls back to single-word tokenizer → emits "will".
353+
assert_eq!(result, vec!["will"]);
354+
}
355+
356+
#[test]
357+
fn longest_first_wins_over_prefix() {
358+
// With both "Will" and "Will Pfleger" known, "@Will Pfleger" should
359+
// match the longer name, not just "Will".
360+
let result = extract_at_mentions_with_known(
361+
"@Will Pfleger sent a message",
362+
&["Will", "Will Pfleger"],
363+
);
364+
assert_eq!(result, vec!["will pfleger"]);
365+
}
366+
367+
#[test]
368+
fn single_word_known_name_matches() {
369+
let result = extract_at_mentions_with_known("ping @alice please", &["Alice"]);
370+
assert_eq!(result, vec!["alice"]);
371+
}
372+
373+
#[test]
374+
fn unknown_name_falls_back_to_single_word() {
375+
// @alice is not in known_names but single-word fallback still emits it.
376+
let result = extract_at_mentions_with_known("hey @alice", &["Bob"]);
377+
assert_eq!(result, vec!["alice"]);
378+
}
379+
380+
#[test]
381+
fn multiple_mentions_mixed_known_and_unknown() {
382+
let result = extract_at_mentions_with_known(
383+
"@Will Pfleger and @alice should review",
384+
&["Will Pfleger"],
385+
);
386+
assert_eq!(result, vec!["will pfleger", "alice"]);
387+
}
388+
389+
#[test]
390+
fn deduplicates_case_insensitively() {
391+
let result = extract_at_mentions_with_known(
392+
"@Will Pfleger and @will pfleger again",
393+
&["Will Pfleger"],
394+
);
395+
assert_eq!(result, vec!["will pfleger"]);
396+
}
397+
398+
#[test]
399+
fn multiword_name_at_end_of_string() {
400+
let result = extract_at_mentions_with_known("cc @Will Pfleger", &["Will Pfleger"]);
401+
assert_eq!(result, vec!["will pfleger"]);
402+
}
403+
404+
#[test]
405+
fn multiword_name_followed_by_punctuation() {
406+
let result =
407+
extract_at_mentions_with_known("thanks @Will Pfleger, great work", &["Will Pfleger"]);
408+
assert_eq!(result, vec!["will pfleger"]);
409+
}
410+
411+
#[test]
412+
fn email_address_not_matched() {
413+
let result = extract_at_mentions_with_known("[email protected]", &["example.com"]);
414+
assert!(result.is_empty());
415+
}
416+
417+
#[test]
418+
fn empty_content_returns_empty() {
419+
let result = extract_at_mentions_with_known("", &["Alice"]);
420+
assert!(result.is_empty());
421+
}
422+
423+
#[test]
424+
fn empty_known_names_uses_single_word_fallback() {
425+
let result = extract_at_mentions_with_known("hey @alice", &[]);
426+
assert_eq!(result, vec!["alice"]);
427+
}
428+
208429
// ── match_names_to_profiles ─────────────────────────────────────────
209430

210431
fn profile<'a>(pk: &'a str, json: &'a str) -> MentionProfile<'a> {

‎desktop/src/shared/lib/mentionPattern.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ export function escapeRegExp(str: string): string {
99
* Build a regex that matches a given prefix followed by known multi-word names
1010
* (longest-first to avoid partial matches). When known names are provided,
1111
* only those names are matched — no generic fallback. When no names are
12-
* available, falls back to prefix + \S+ for backwards compatibility (e.g.
13-
* old messages without proper p-tags, or while profiles are loading).
12+
* available, returns a never-matching regex so that arbitrary prefix+word
13+
* patterns are not highlighted as if they were valid matches (e.g. @Will
14+
* should not render as a mention when only "Will Pfleger" is a real user).
1415
*/
1516
export function buildPrefixPattern(
1617
prefix: string,
@@ -23,7 +24,10 @@ export function buildPrefixPattern(
2324
const escapedPrefix = escapeRegExp(prefix);
2425

2526
if (sorted.length === 0) {
26-
return new RegExp(`${escapedPrefix}\\S+`, "gi");
27+
// No known names — don't highlight anything as a mention.
28+
// Previously fell back to prefix+\S+ which created false positives for
29+
// messages without p-tags or with unresolved multi-word display names.
30+
return /(?!)/gi; // never matches
2731
}
2832

2933
const nameAlternatives = sorted.map((name) => escapeRegExp(name)).join("|");
@@ -32,8 +36,10 @@ export function buildPrefixPattern(
3236
}
3337

3438
/**
35-
* Build a regex that matches @mentions, trying known multi-word names first
36-
* (longest-first to avoid partial matches), then falling back to @\S+.
39+
* Build a regex that matches @mentions for known multi-word names
40+
* (longest-first to avoid partial matches). When no known names are provided,
41+
* returns a never-matching regex — @word patterns are not highlighted unless
42+
* they correspond to an actual p-tagged member.
3743
*/
3844
export function buildMentionPattern(mentionNames: string[]): RegExp {
3945
return buildPrefixPattern("@", mentionNames);

0 commit comments

Comments
 (0)