mirror of
https://github.com/block/buzz.git
synced 2026-11-30 21:21:48 +00:00
## Summary The mobile composer's @mention typing was an older port of the mention rules that [block/buzz-app](https://github.com/block/buzz-app) follows (`src/bundled/mentions/README.md` there), and it trailed buzz-app in nine places. Most of them came from one difference: mobile tied a picked person to the `@Label` text and looked for that text again at send time, while buzz-app keeps the recipient on an atomic chip. Several of the gaps meant a picked person was silently not notified. This PR fixes all nine. Every change is in `mobile/`; no relay, CLI or desktop code is touched, and the event payloads mobile writes keep the same shape. ### Commits | Commit | Fixes | What it changes | |---|---|---| |9152e91fe| 1, 2 | Picked people are atomic chips, as agents already were. The recipient comes from the chips, so a pick after `(`, `[` or `{` notifies. Backspace removes the trailing space, then the whole chip; arrows step over a chip. | |2cbdabdae| 3, 4 | A chip is bound to its recipient by its position in the draft and keeps it through punctuation, apostrophes, hyphens and slashes. Namesake chips read `@Sam · a1b2`, and the draft text never holds a public key. | |c4d3f2072| 5 | A chip's `@` never opens a query, so prose typed after a pick sends no directory searches. A query that found nobody refutes every longer query that continues it. | |4e4ac3efd| 6 | Name matching folds accents, full-width letters and ligatures, and breaks words on hyphens and apostrophes. The vendored contract fixture moves from version 1 to version 4, and all 125 cases pass. | |38e8f2e1e| 7 | Closing punctuation (`. , ! ? ; :`, `)`, `]`, `}` and closing quotes) selects an exact, unique name as Space does, and the character stays after the chip. | |e008151c6| 8 | The chooser is shown only while the text field has focus. The query and its rows are kept while hidden, so refocusing shows the same rows without a new search. | |199606969| 9 | The edit sheet mounts the composer's chooser through a shared hook. A pick inserts a chip, and the saved edit adds no `p` tag. | |a1e4d69fa| 3 | The message renderer ends a mention where the composer does, so a sent `@Honey's report` draws Honey's pill with the suffix as text. | |bf34af139| 2 | iOS reports one Backspace as two editing updates (select the character, then delete the selection). The controller recognises that pair and removes the whole chip and its binding. | ### How to read the videos Each video has three columns that follow the same numbered steps with the same people and the same typed text: mobile before this PR on the left, mobile on this branch in the middle, and buzz-app on the right. The bar across the top names the current step, and a column that finishes a step early holds its frame until the others catch up. The dark panel on each phone is a readout added for the recording. Its `p tags (notified)` line shows who a sent message would notify, and `directory searches sent` counts requests to the directory. The readout under the buzz-app composer shows the same facts. ### 1. A mention picked after a bracket keeps its recipient `see (@Honey) please` went out with nobody notified, because the send-time scan did not accept the brackets the chooser did. The recipient now comes from the chip, and the typed-name fallback accepts `(`, `[` and `{` too. https://github.com/user-attachments/assets/b1f1c76b-b991-4f90-9079-a435c4475c2b ### 2. People mentions are atomic chips A second Backspace used to leave plain `@Hone` (and `@Scou` for the agent), which sent with no recipient. Now the first Backspace removes the trailing space and the second removes the whole chip, and the arrow keys step over a chip as one unit. https://github.com/user-attachments/assets/a198656c-d735-46a7-a954-9e0aa4af7dc3 ### 3. A suffix after a mention keeps the recipient `@Honey's report` and `@Honey-bot is back` notified nobody. A chip now survives an apostrophe (straight or curly), a hyphen, a slash or punctuation typed against it, and the sent bubble draws the pill with the suffix as text. Only a letter, mark, digit or underscore typed against the chip unbinds it. https://github.com/user-attachments/assets/c481110d-1633-4c01-9810-a8d750ce2ae2 ### 4. No raw public key in the composer Picking two people with the same name filled the draft with two 64-character keys. Each pick is now a chip with a short label, the draft text stays `@Honey`, and each namesake gets their own `p` tag. The key suffixes on the labels differ between the apps only because each recording generated its own keys. https://github.com/user-attachments/assets/4f56cddd-a96f-43cb-820b-511eb965a77b ### 5. No directory search while typing prose Every character of a sentence typed after a pick was sent to the directory as a name search: 20 searches in this clip. The count now stays at 1, the same as buzz-app. A short query with no local match still searches, so a person outside the channel is still found. https://github.com/user-attachments/assets/3575b2cf-e3a6-42f1-9779-6e1401f00dfc ### 6. Accent folding and contract fixture version 4 `@jose` could not find José María, so `@jose maria` went out as plain text. Names now fold accents, the row stays listed, and the pick is a chip that notifies José María. The vendored fixture is version 4 of the shared contract, copied unchanged, with no case skipped. https://github.com/user-attachments/assets/362f6b4b-a09c-4f69-910e-8903408be77e ### 7. Closing punctuation selects an exact name A comma typed straight after `@Honey` or `@Outside Person` joined the query and closed the chooser; for a person outside the channel the message went out with no recipient and no prompt. The comma now selects the exact name, and Send shows the outside-channel prompt, where Invite adds the person and sends with their `p` tag. https://github.com/user-attachments/assets/b43a0663-489f-4ae3-ae36-7a2a92443f9e ### 8. The chooser follows the field's focus Dragging the keyboard away collapsed the composer but left the chooser row floating above it. The chooser now hides when the field loses focus and returns with the same rows when focus comes back. Step 1 of the mobile columns is sped up three times, because the on-screen keyboard is slow to drive in the simulator. https://github.com/user-attachments/assets/2ce0093d-03d0-4792-9b05-fb28980830fc ### 9. The chooser works in the edit sheet The edit sheet was a plain text field with no chooser. It now uses the composer's chooser with the same rules, and existing mentions open as chips. The saved edit adds no `p` tag, matching buzz-app's rule that an edit notifies nobody. https://github.com/user-attachments/assets/e54d5620-ae2d-49b5-8cce-99536b8d81db ### Known gaps left for follow-up - **Typed, unpicked names.** Mobile still notifies a typed name that equals exactly one member and refuses to send an ambiguous one. buzz-app does not do either, and the shared contract has not settled which is right. - **Directory-only names selected before the search finishes.** Space or closing punctuation selects a directory-only name as soon as it is in the ranked rows. buzz-app waits until that query's search has finished. This predates the PR for Space and now also applies to punctuation. - **Undo does not restore a chip.** After a letter typed against a chip unbinds it, Undo restores the text but not the chip. iOS shake-to-undo also bypasses the new undo detection. - **Edits drop existing tags.** The timeline reads mention tags from the edit event, so editing a message that already tagged someone still loses that pill. Carrying the original tags through an edit is a separate change. - **`_@Name_` italics.** `_` now counts as a name character, as in buzz-app, so `_@Honey_` no longer draws a pill. ### Related issue N/A. None found; #9008 made the relay's name search accent-insensitive, and fix 6 does the same for matching on the device. ### Testing - `dart format`, `flutter analyze`, `just file-size-check` and the full mobile `flutter test` suite passed on every commit. Two timing-sensitive tests unrelated to mentions (relay socket liveness, community snapshot cleanup) each failed once under full-suite load and passed solo. - Each fix has a widget-test journey through the real composer, chooser and send path, and each was shown to fail with its fix removed. The shared contract fixture runs in full. - The videos are harness recordings on an iPhone 17 simulator (iOS 27.2): the real channel page, composer, chooser, edit sheet and send path on an in-memory relay, not the app against a live community. The buzz-app column is a headless WebKit recording of buzz-app's fixture pages. - Android and physical devices were not exercised. - The branch was pushed with `--no-verify`, so the pre-push lanes did not run locally. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Matt Toohey <contact@matttoohey.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
293 lines
10 KiB
Dart
293 lines
10 KiB
Dart
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 4).
|
||
@immutable
|
||
class MentionChoice {
|
||
/// Lowercase 64-hex public key.
|
||
final String pubkey;
|
||
|
||
/// The identity's own name.
|
||
final String name;
|
||
|
||
/// The name shown in the chooser. It can be qualified or a key fallback.
|
||
final String label;
|
||
|
||
/// The real names known for this key. Empty when no name is known.
|
||
final List<String> aliases;
|
||
final bool member;
|
||
final bool agent;
|
||
|
||
/// Ownership is a display hint from profile metadata, not authorization.
|
||
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,
|
||
required this.label,
|
||
required this.aliases,
|
||
required this.member,
|
||
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];
|
||
}
|
||
|
||
List<int> _runes(String needle) => needle.runes.toList();
|
||
|
||
int? _min(Iterable<int?> values) {
|
||
int? best;
|
||
for (final value in values) {
|
||
if (value != null && (best == null || value < best)) best = value;
|
||
}
|
||
return best;
|
||
}
|
||
|
||
int? _baseMatch(MentionChoice choice, List<int> needle) =>
|
||
_min(choice.aliases.map((name) => foldedNameMatchTier(name, needle)));
|
||
|
||
/// [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 = 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. 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,
|
||
String query, {
|
||
Map<String, int> history = const {},
|
||
String Function(String pubkey)? presence,
|
||
}) {
|
||
final needle = normalizeName(query);
|
||
final needleRunes = _runes(needle);
|
||
final key = typedPublicKey(query);
|
||
final keyed = <_Keyed>[];
|
||
for (final choice in choices) {
|
||
final match = needle.isEmpty ? 0 : _labelMatch(choice, needleRunes, key);
|
||
if (match == null) continue;
|
||
final status = presence?.call(choice.pubkey);
|
||
keyed.add(
|
||
_Keyed(
|
||
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, needleRunes) ?? 1 << 30,
|
||
choice.agent && choice.owned ? 0 : 1,
|
||
],
|
||
label: normalizeName(choice.label),
|
||
blockName: choice.agent ? normalizeName(choice.name) : null,
|
||
recent: history[choice.pubkey] ?? 0,
|
||
online: switch (status) {
|
||
'online' => 0,
|
||
'away' => 1,
|
||
_ => 2,
|
||
},
|
||
),
|
||
);
|
||
}
|
||
final firstLabel = <String, String>{};
|
||
for (final k in keyed) {
|
||
final label = firstLabel[k.block];
|
||
if (label == null || _compare(k.label, label) < 0) {
|
||
firstLabel[k.block] = k.label;
|
||
}
|
||
}
|
||
keyed.sort((a, b) {
|
||
for (var i = 0; i < a.tier.length; i++) {
|
||
final d = a.tier[i] - b.tier[i];
|
||
if (d != 0) return d;
|
||
}
|
||
var d = _compare(firstLabel[a.block]!, firstLabel[b.block]!);
|
||
if (d != 0) return d;
|
||
// People never join a block. On an equal block label they sort first.
|
||
d = (a.blockName == null ? 0 : 1) - (b.blockName == null ? 0 : 1);
|
||
if (d != 0) return d;
|
||
d = a.blockName == null
|
||
? _compare(a.choice.pubkey, b.choice.pubkey)
|
||
: _compare(a.blockName!, b.blockName!);
|
||
if (d != 0) return d;
|
||
d = b.recent - a.recent;
|
||
if (d != 0) return d;
|
||
d = (b.choice.managed ? 1 : 0) - (a.choice.managed ? 1 : 0);
|
||
if (d != 0) return d;
|
||
d = a.online - b.online;
|
||
if (d != 0) return d;
|
||
d = _compare(a.label, b.label);
|
||
if (d != 0) return d;
|
||
return _compare(a.choice.pubkey, b.choice.pubkey);
|
||
});
|
||
return [for (final k in keyed) k.choice];
|
||
}
|
||
|
||
class _Keyed {
|
||
final MentionChoice choice;
|
||
final List<int> tier;
|
||
final String label;
|
||
|
||
/// Normalized name for an agent, null for a person.
|
||
final String? blockName;
|
||
final int recent;
|
||
final int online;
|
||
|
||
_Keyed({
|
||
required this.choice,
|
||
required this.tier,
|
||
required this.label,
|
||
required this.blockName,
|
||
required this.recent,
|
||
required this.online,
|
||
});
|
||
|
||
late final String block = blockName == null
|
||
? '0${choice.pubkey}'
|
||
: '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. 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 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) {
|
||
if (choice.aliases.isNotEmpty && _hasExactName(choice, needle)) {
|
||
count++;
|
||
found = choice.pubkey;
|
||
}
|
||
}
|
||
return count == 1 ? found : null;
|
||
}
|
||
|
||
final _mentionTerminators = RegExp(r'''^[ .,!?;:)\]}'’"”]$''', unicode: true);
|
||
|
||
/// Section 5: whether [character], typed straight after a query, selects
|
||
/// its exact, unique name as Space does. Besides Space: closing punctuation,
|
||
/// a closing bracket for the ones a query opens after, or a closing quote,
|
||
/// so `@Bob,` and `@Bob's` mention Bob. The client keeps the character after
|
||
/// the mention in place of the space. Where Space would not select, the
|
||
/// character is typed into the query instead: `'` after `Pat O` while
|
||
/// `Pat O'Brien` is known stays in the query. Any other character, such as
|
||
/// a hyphen, is never a terminator.
|
||
bool mentionTerminator(String character) =>
|
||
_mentionTerminators.hasMatch(character);
|
||
|
||
/// An open `@` query: `[start, end)` covers `@` and the query text.
|
||
typedef MentionQuery = ({int start, int end, String query});
|
||
|
||
final _queryPattern = RegExp(r'(?:^|[\s(\[{])@([^@\n\r\t]*)$', unicode: true);
|
||
final _boundary = RegExp(r'[\s(\[{]', unicode: true);
|
||
|
||
/// Section 2 syntax only. Multi-word queries are admitted separately by
|
||
/// [matchesMentionQuery] against current names.
|
||
MentionQuery? findMentionQuery(String text, int caret) {
|
||
if (caret < 0 || caret > text.length) return null;
|
||
final before = text.substring(caret > 160 ? caret - 160 : 0, caret);
|
||
final match = _queryPattern.firstMatch(before);
|
||
if (match == null) return null;
|
||
final query = match.group(1) ?? '';
|
||
final start = caret - query.length - 1;
|
||
// A bounded slice that begins inside a word is not a boundary.
|
||
if (start > 0 && !_boundary.hasMatch(text[start - 1])) return null;
|
||
return (start: start, end: caret, query: query);
|
||
}
|
||
|
||
/// Section 2 multi-word rule: a query with a space stays open only while it
|
||
/// 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 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));
|
||
}
|