fix(mobile): fold accents when matching mention names

`@jos` listed José María, `@jose` listed nobody and `@josé` listed them
again: mobile only lowercased names. Name matching now follows section 3
of the shared mention rules, as buzz-app does (recommendation 6). Each
code point is NFKD-normalized, its combining accents (the Combining
Diacritical Marks blocks) are removed, it is lowercased and a final `ς`
becomes `σ`, so `jose` matches `José`, `fiona` matches `fio` and `jose`
matches `jose`, while `ø`, `ł`, `æ`, `ß`, `ı` and the marks of other
scripts stay distinct. Words are runs of letters, marks and digits, so a
hyphen or apostrophe separates them: `jane` finds `Mary-Jane` and `brien`
finds `O'Brien`. The folding lives in `name_match.dart` and drives the
chooser, Space selection, multi-word admission, the verified-name matches
and the recipient pickers, so `@jose maria` lists José María with no
accents typed.

The vendored fixture moves from version 1 (95 cases) to version 4 of
buzz-app's `mention-rules.fixtures.json` (125 cases), copied unchanged,
and the conformance test runs every section, with a new `matching` group.
No case is skipped. The rules the newer versions added are implemented
too: an exact public key (64 hex in either case, or a complete lowercase
or uppercase npub with an optional `nostr:` prefix) matches only its
owner, even one with no name, and Space selects that owner; the viewer's
own agent whose name continues the query with a new word leads (`Sol 6`
for `sol`), and an exact person leads over it; agents from the viewer's
other communities follow everyone here; an outside choice's longer name
no longer blocks a member's exact name on Space, and a choice's own longer
alias is not its own namesake.

The search cache's exact-key exemption uses the same `typedPublicKey`.
Refutation itself stays lowercase-only on purpose: it reasons about the
relay's prefix search, which is out of scope here, so an accented query
is a new search rather than a continuation. A refuted query still matches
members on the device by folding: after `z` finds nobody, `@zoe` lists
the member Zoë without a search.

Tests: the compose bar search journey types `@jose maria` and sees José
María, and `@zoe` after the `z` refutation sees Zoë; both and seven
fixture cases fail when accent stripping is removed. `dart format`,
`flutter analyze` and the full mobile `flutter test` suite pass.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Matt Toohey <contact@matttoohey.com>
This commit is contained in:
Matt Toohey
2026-11-17 18:37:47 +11:00
parent c4d3f2072b
commit 4e4ac3efd8
7 changed files with 1087 additions and 61 deletions

View File

@@ -7,6 +7,7 @@ import '../../../shared/identity_names/identity_names.dart';
import '../../../shared/identity_names/identity_names_provider.dart';
import '../../../shared/mentions/agent_identity_provider.dart';
import '../../../shared/relay/relay.dart';
import '../../../shared/utils/string_utils.dart';
import '../../../shared/profile/user_cache_provider.dart';
import '../../../shared/profile/user_profile.dart';
import '../../../shared/verified_profiles/verified_profile.dart';
@@ -103,13 +104,16 @@ class MentionSearchCache {
/// The last finished search that found nobody, or null.
String? _refuted;
/// Lowercase only, not the section 3 folding: the directory is the relay's
/// search, whose prefix rule is what a refutation reasons about, so an
/// accented query is a different search, not a continuation of the plain
/// one. The device still matches members and found people by folding.
static String _key(String query) => query.trim().toLowerCase();
/// Only a query with a letter or digit searches names; a public key is an
/// author lookup that no name prefix can refute.
/// Only a query with a letter or digit searches names; an exact public key
/// is an author lookup that no name prefix can refute.
static final _wordCharacter = RegExp(r'[\p{L}\p{N}]', unicode: true);
static final _npub = RegExp(r'^(?:nostr:)?npub1[02-9ac-hj-np-z]{58}$');
static bool _exactKey(String key) => isMentionKey(key) || _npub.hasMatch(key);
static bool _exactKey(String key) => typedPublicKey(key) != null;
/// Whether the last finished search found nobody for a shorter query that
/// [query] continues, so a search for [query] would find nobody either.

View File

@@ -1,7 +1,10 @@
import 'package:flutter/foundation.dart';
import '../utils/string_utils.dart';
import 'name_match.dart';
/// One key the user can mention. The fields are the inputs of the portable
/// mention rules (buzz-app `src/bundled/mentions/README.md`, version 1).
/// mention rules (buzz-app `src/bundled/mentions/README.md`, version 4).
@immutable
class MentionChoice {
/// Lowercase 64-hex public key.
@@ -22,6 +25,10 @@ class MentionChoice {
final bool owned;
final bool managed;
/// The other community this agent of the viewer's comes from, or null for
/// a choice of this community (section 4, rule 2).
final String? elsewhere;
const MentionChoice({
required this.pubkey,
required this.name,
@@ -31,24 +38,14 @@ class MentionChoice {
this.agent = false,
this.owned = false,
this.managed = false,
this.elsewhere,
});
/// Every name of this choice: its aliases and its label.
List<String> get _names => [...aliases, label];
}
String _normalized(String text) => text.trim().toLowerCase();
final _whitespace = RegExp(r'\s+', unicode: true);
/// Tier 0 to 3 from section 3, or null for no match.
int? _nameMatch(String text, String needle) {
if (needle.isEmpty) return 0;
final name = _normalized(text);
if (name == needle) return 0;
if (name.startsWith(needle)) return 1;
final words = name.split(_whitespace);
if (words.contains(needle)) return 2;
if (words.any((word) => word.startsWith(needle))) return 3;
return null;
}
List<int> _runes(String needle) => needle.runes.toList();
int? _min(Iterable<int?> values) {
int? best;
@@ -58,27 +55,52 @@ int? _min(Iterable<int?> values) {
return best;
}
int? _baseMatch(MentionChoice choice, String needle) =>
_min(choice.aliases.map((name) => _nameMatch(name, needle)));
int? _baseMatch(MentionChoice choice, List<int> needle) =>
_min(choice.aliases.map((name) => foldedNameMatchTier(name, needle)));
/// A choice's match (section 3): the label tier, else 4 plus the best alias
/// tier. Null means the choice does not match. Keys are never searchable.
@visibleForTesting
int? mentionMatch(MentionChoice choice, String query) {
final needle = _normalized(query);
if (needle.isEmpty) return 0;
/// [mentionMatch] for a normalized, non-empty [needle] and the query's
/// exact public [key], if it is one.
int? _labelMatch(MentionChoice choice, List<int> needle, String? key) {
// An exact public key is not a name: it matches only its owner.
if (key != null) return choice.pubkey == key ? 0 : null;
// No known name: the label is only a key fallback.
if (choice.aliases.isEmpty) return null;
final visible = _nameMatch(choice.label, needle);
final visible = foldedNameMatchTier(choice.label, needle);
if (visible != null) return visible;
final base = _baseMatch(choice, needle);
return base == null ? null : 4 + base;
}
/// A choice's match (section 3): the label tier, else 4 plus the best alias
/// tier. Null means the choice does not match. Keys are never searchable,
/// except an exact public key, which matches only the choice it names.
@visibleForTesting
int? mentionMatch(MentionChoice choice, String query) {
final needle = normalizeName(query);
if (needle.isEmpty) return 0;
return _labelMatch(choice, _runes(needle), typedPublicKey(query));
}
/// Section 4 rule 3: a choice whose shown label matches the query leads when
/// one of its names (aliases, never generated label parts) is the query, or,
/// for the viewer's own agent, continues it with a new word (`Sol 6` for
/// `sol`, not `Solana`). [needle] is normalized and non-empty.
bool _leads(MentionChoice choice, String needle, List<int> needleRunes) {
if (choice.agent && !choice.owned) return false;
if (foldedNameMatchTier(choice.label, needleRunes) == null) return false;
return choice.aliases.any(
(name) =>
normalizeName(name) == needle ||
(choice.agent && nameContinues(name, needle)),
);
}
int _compare(String a, String b) => a.compareTo(b);
/// Section 4 order. Every rule is a key of one choice, so the result is the
/// same for any input order. Agents that share a name form one block at its
/// same for any input order. Another community's agents follow everyone
/// here; an exact person and the viewer's own agents that start with the
/// query's words lead. Agents that share a name form one block at its
/// lowest label; recency, managed and presence order only that block.
List<MentionChoice> rankMentions(
Iterable<MentionChoice> choices,
@@ -86,10 +108,12 @@ List<MentionChoice> rankMentions(
Map<String, int> history = const {},
String Function(String pubkey)? presence,
}) {
final needle = _normalized(query);
final needle = normalizeName(query);
final needleRunes = _runes(needle);
final key = typedPublicKey(query);
final keyed = <_Keyed>[];
for (final choice in choices) {
final match = mentionMatch(choice, query);
final match = needle.isEmpty ? 0 : _labelMatch(choice, needleRunes, key);
if (match == null) continue;
final status = presence?.call(choice.pubkey);
keyed.add(
@@ -97,13 +121,15 @@ List<MentionChoice> rankMentions(
choice: choice,
tier: [
choice.member ? 0 : 1,
choice.elsewhere == null ? 0 : 1,
needle.isNotEmpty && _leads(choice, needle, needleRunes) ? 0 : 1,
match,
// No aliases: after every named choice, even for the empty query.
_baseMatch(choice, needle) ?? 1 << 30,
_baseMatch(choice, needleRunes) ?? 1 << 30,
choice.agent && choice.owned ? 0 : 1,
],
label: _normalized(choice.label),
blockName: choice.agent ? _normalized(choice.name) : null,
label: normalizeName(choice.label),
blockName: choice.agent ? normalizeName(choice.name) : null,
recent: history[choice.pubkey] ?? 0,
online: switch (status) {
'online' => 0,
@@ -171,17 +197,48 @@ class _Keyed {
: '1${tier.join(',')}\u0000$blockName';
}
bool _hasExactName(MentionChoice choice, String needle) =>
choice._names.any((name) => normalizeName(name) == needle);
/// Section 5: whether a known longer name keeps the query's exact name from
/// selecting. Once a member has the exact name, only another member's longer
/// name does: a choice outside the channel never makes a member's name
/// ambiguous. A choice's own longer name does not count when that same
/// choice also has the exact name (`Example Agent` beside `Example`), nor
/// does a generated `(agent)` suffix on its label.
bool _continued(Iterable<MentionChoice> choices, String needle) {
final member = choices.any(
(c) => c.member && c.aliases.isNotEmpty && _hasExactName(c, needle),
);
for (final choice in choices) {
if (member && !choice.member) continue;
if (_hasExactName(choice, needle)) continue;
final longer =
choice.agent &&
choice.aliases.any(
(name) => '${name.trim()} (agent)' == choice.label,
)
? choice.aliases
: choice._names;
if (longer.any((name) => nameContinues(name, needle))) return true;
}
return false;
}
/// Section 5: the key Space selects, or null. Checked against the full,
/// uncapped choice set.
/// uncapped choice set. An exact public key names only its owner, even one
/// with no known name, and no name continues it.
String? exactMention(Iterable<MentionChoice> choices, String query) {
final needle = _normalized(query);
if (needle.isEmpty) return null;
final key = typedPublicKey(query);
if (key != null) {
return choices.where((choice) => choice.pubkey == key).firstOrNull?.pubkey;
}
final needle = normalizeName(query);
if (needle.isEmpty || _continued(choices, needle)) return null;
String? found;
var count = 0;
for (final choice in choices) {
final names = [...choice.aliases, choice.label].map(_normalized);
if (names.any((name) => name.startsWith('$needle '))) return null;
if (choice.aliases.isNotEmpty && names.contains(needle)) {
if (choice.aliases.isNotEmpty && _hasExactName(choice, needle)) {
count++;
found = choice.pubkey;
}
@@ -210,14 +267,13 @@ MentionQuery? findMentionQuery(String text, int caret) {
}
/// Section 2 multi-word rule: a query with a space stays open only while it
/// is still the start of a known name. A complete name plus a trailing space
/// is prose.
/// is still the start of a known name, compared after section 3 folding of
/// the names. The query itself is not trimmed: a complete name plus a
/// trailing space is prose.
bool matchesMentionQuery(String query, Iterable<String> names) {
if (!query.contains(' ')) return true;
final lower = query.toLowerCase();
if (lower.endsWith(' ') &&
names.any((name) => name.toLowerCase() == lower.trimRight())) {
return false;
}
return names.any((name) => name.toLowerCase().startsWith(lower));
final folded = foldName(query);
final known = names.map(normalizeName).toList();
if (folded.endsWith(' ') && known.contains(folded.trimRight())) return false;
return known.any((name) => name.startsWith(folded));
}

View File

@@ -0,0 +1,129 @@
/// The one rule for matching a typed name to a person or agent name: the
/// portable mention rules, section 3 (buzz-app
/// `src/bundled/mentions/README.md`). Mentions, Space selection, query
/// admission and the recipient pickers all use it, so the same text finds
/// the same people, and `jose` finds `José`.
///
/// Normalization per code point: Unicode NFKD, the combining accents of the
/// "Combining Diacritical Marks" blocks removed, lowercase, and `ς` as `σ`.
/// Other marks stay, since in many scripts a mark makes a different letter
/// (`राम` is not `रम`, `ジョン` is not `ション`), and letters without a
/// decomposition do not fold (`ø`, `ł`, `æ`, `ß` and `ı` stay themselves).
/// This is deliberately narrower than platform diacritic-insensitive or full
/// case-folding comparisons, which the contract forbids.
library;
import 'package:unorm_dart/unorm_dart.dart' as unorm;
bool _isAccent(int rune) =>
(rune >= 0x0300 && rune <= 0x036F) ||
(rune >= 0x1AB0 && rune <= 0x1AFF) ||
(rune >= 0x1DC0 && rune <= 0x1DFF) ||
(rune >= 0x20D0 && rune <= 0x20FF) ||
(rune >= 0xFE20 && rune <= 0xFE2F);
/// Folds one non-ASCII code point.
String _foldPoint(String char) {
final buffer = StringBuffer();
for (final rune in unorm.nfkd(char).runes) {
if (!_isAccent(rune)) buffer.writeCharCode(rune);
}
return buffer.toString().toLowerCase().replaceAll('ς', 'σ');
}
/// Folding is the cost of matching, and the same names meet a new query on
/// every keystroke, so folded names stay folded. Long names are not kept.
final _folded = <String, String>{};
const _foldedLimit = 4096;
const _foldedLength = 128;
/// [text] without accents and case, as section 3 says. Keeps the spaces at
/// its ends, which query admission needs.
String foldName(String text) {
final cached = _folded[text];
if (cached != null) return cached;
final buffer = StringBuffer();
for (final rune in text.runes) {
if (rune < 0x80) {
// ASCII has no accents, decompositions or final sigma.
buffer.writeCharCode(rune >= 0x41 && rune <= 0x5A ? rune + 0x20 : rune);
} else {
buffer.write(_foldPoint(String.fromCharCode(rune)));
}
}
final folded = buffer.toString();
if (text.length <= _foldedLength) {
if (_folded.length >= _foldedLimit) _folded.clear();
_folded[text] = folded;
}
return folded;
}
/// The form for comparing and ordering names: [foldName], trimmed.
String normalizeName(String text) => foldName(text).trim();
final _wordCharacter = RegExp(r'^[\p{L}\p{M}\p{N}]$', unicode: true);
final _whitespace = RegExp(r'\s', unicode: true);
/// A word is a run of letters, marks and digits; every other code point
/// separates words, so `jane` finds `Mary-Jane` and `brien` finds `O'Brien`.
bool isNameWordCharacter(int rune) {
if (rune < 0x80) {
return (rune >= 0x30 && rune <= 0x39) ||
(rune >= 0x41 && rune <= 0x5A) ||
(rune >= 0x61 && rune <= 0x7A);
}
return _wordCharacter.hasMatch(String.fromCharCode(rune));
}
bool _startsAt(List<int> chars, List<int> needle, int from) {
if (from + needle.length > chars.length) return false;
for (var i = 0; i < needle.length; i++) {
if (chars[from + i] != needle[i]) return false;
}
return true;
}
/// Section 3 tier of [name] for a query whose [normalizeName] runes are
/// [needle], or null for no match. An empty query matches at tier 0.
int? foldedNameMatchTier(String name, List<int> needle) {
if (needle.isEmpty) return 0;
final chars = normalizeName(name).runes.toList();
if (chars.length == needle.length && _startsAt(chars, needle, 0)) return 0;
if (chars.length > needle.length && _startsAt(chars, needle, 0)) return 1;
// A later word: the match starts where a word starts, and is that whole
// word (tier 2) when it also ends where the word ends. A query with a
// space matches only from the start of the name.
if (needle.any((rune) => _whitespace.hasMatch(String.fromCharCode(rune)))) {
return null;
}
var prefix = false;
for (var from = 1; from < chars.length; from++) {
if (!isNameWordCharacter(chars[from]) ||
isNameWordCharacter(chars[from - 1]) ||
!_startsAt(chars, needle, from)) {
continue;
}
final stop = from + needle.length;
if (stop >= chars.length || !isNameWordCharacter(chars[stop])) return 2;
prefix = true;
}
return prefix ? 3 : null;
}
/// Section 3 tier of [name] for [query], or null for no match.
int? nameMatchTier(String name, String query) =>
foldedNameMatchTier(name, normalizeName(query).runes.toList());
/// Whether [name] is longer than the normalized query [needle] and continues
/// it with a new word, as `Jose Luis` and `Jose-Luis` continue `jose` but
/// `Josefa` does not. Such a name keeps Space from selecting a shorter exact
/// name (section 5).
bool nameContinues(String name, String needle) {
if (needle.isEmpty) return false;
final whole = normalizeName(name).runes.toList();
final query = needle.runes.toList();
return whole.length > query.length &&
_startsAt(whole, query, 0) &&
!isNameWordCharacter(whole[query.length]);
}

View File

@@ -50,6 +50,34 @@ String? fullNpub(String identity) {
}
}
/// The hex public key that typed text names exactly (portable mention rules,
/// Terms): 64 hex characters in either case, or a complete all-lowercase or
/// all-uppercase npub, with or without a `nostr:` prefix in any case. Null
/// for anything else, including a key still being typed, a mixed-case npub,
/// or one with a bad checksum or a payload of another length.
String? typedPublicKey(String text) {
final value = text.trim();
if (isHexPubkey(value)) return value.toLowerCase();
const scheme = 'nostr:';
final npub =
value.length > scheme.length &&
value.substring(0, scheme.length).toLowerCase() == scheme
? value.substring(scheme.length)
: value;
if (!npub.toLowerCase().startsWith('npub1')) return null;
try {
// bech32 rejects mixed case itself.
final decoded = nostr.Nip19.decode(payload: npub);
if (decoded.prefix != nostr.Nip19Prefix.npub ||
!isHexPubkey(decoded.data)) {
return null;
}
return decoded.data.toLowerCase();
} catch (_) {
return null;
}
}
/// Encoded npubs by lowercase hex key. Identity views label every roster
/// member without a profile name by npub on each rebuild, and bech32 encoding
/// dominated those rebuilds on large channels. Bounded: once full it keeps