Files
buzz/mobile/test/features/channels/quick_send_test.dart
Matt Toohey 2074adaa85 fix(mobile): bring @mention typing in line with buzz-app (#9699)
## 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>
2026-11-20 21:12:49 +00:00

361 lines
11 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:buzz/shared/drafts/compose_drafts_provider.dart';
import 'package:buzz/features/channels/channel.dart';
import 'package:buzz/features/channels/channels_provider.dart';
import 'package:buzz/features/channels/quick_send_host.dart';
import 'package:buzz/shared/me/default_agent.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:buzz/shared/theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nostr/nostr.dart' as nostr;
import 'package:shared_preferences/shared_preferences.dart';
class _EmptyChannels extends ChannelsNotifier {
@override
Future<List<Channel>> build() async => [];
}
class _Lifecycle extends AppLifecycleNotifier {
@override
AppLifecycleState build() => AppLifecycleState.resumed;
void background() => state = AppLifecycleState.paused;
}
class _Config extends RelayConfigNotifier {
_Config(this.config);
final RelayConfig config;
@override
RelayConfig build() => config;
}
/// A relay that is not connected until the test says so, accepts every
/// publish and serves back the DM its open command finds or creates.
class _Relay extends RelaySessionNotifier {
_Relay(this.owner);
final nostr.Keys owner;
final published = <NostrEvent>[];
/// Rejects the next message the way an over-quota relay does.
var rateLimitNextMessage = false;
/// Loses the next message's answer, so it may or may not have landed.
var timeOutNextMessage = false;
/// Drops the socket just before the next message goes out.
var dropBeforeNextMessage = false;
final _stored = <NostrEvent>[];
static const dmId = 'bestie-dm';
@override
SessionState build() =>
const SessionState(status: SessionStatus.disconnected);
void connect() => state = const SessionState(status: SessionStatus.connected);
/// Background pauses started; the real session closes the socket after one.
var pauses = 0;
@override
void onAppPaused() => pauses++;
@override
void onAppResumed() => connect();
NostrEvent _sign(int kind, List<List<String>> tags) => NostrEvent.fromJson(
nostr.Event.from(
kind: kind,
content: '',
secretKey: owner.secret,
tags: tags,
).toMap(),
);
@override
Future<List<NostrEvent>> queryRelay(
List<NostrFilter> filters, {
Duration timeout = const Duration(seconds: 8),
}) async => const [];
@override
Future<List<NostrEvent>> fetchHistory(
NostrFilter filter, {
Duration timeout = const Duration(seconds: 8),
}) async {
final ds = filter.tags['#d'];
return _stored.reversed
.where(
(e) =>
filter.kinds.contains(e.kind) &&
(ds == null || ds.contains(e.getTagValue('d'))),
)
.take(filter.limit)
.toList();
}
@override
Future<void Function()> subscribeWithStatus(
NostrFilter filter,
void Function(NostrEvent) onEvent, {
void Function(String message)? onClosed,
required void Function(RelaySubscriptionStatus status) onStatusChanged,
bool resumeSince = true,
}) async => () {};
@override
Future<NostrEvent> publish(
NostrEvent event, {
Duration timeout = const Duration(seconds: 8),
Future<bool> Function()? mayPublish,
}) async {
if (event.kind == 9 && rateLimitNextMessage) {
rateLimitNextMessage = false;
throw Exception('rate-limited: quota exceeded; retry in 0s');
}
if (event.kind == 9 && dropBeforeNextMessage) {
dropBeforeNextMessage = false;
throw StateError('Relay session is not connected');
}
if (event.kind == 9 && timeOutNextMessage) {
timeOutNextMessage = false;
throw TimeoutException('no OK');
}
published.add(event);
if (event.kind != 41010) return event;
// Opening is find-or-create: the relay answers with the one DM.
if (!_stored.any((e) => e.getTagValue('d') == dmId)) {
final peer = event.getTagValue('p')!;
_stored.add(
_sign(39000, [
['d', dmId],
['name', 'DM'],
['t', 'dm'],
['private'],
['hidden'],
['p', owner.public],
['p', peer],
]),
);
_stored.add(
_sign(39002, [
['d', dmId],
['p', owner.public, '', 'member'],
['p', peer, '', 'bot'],
]),
);
}
return NostrEvent(
id: event.id,
pubkey: event.pubkey,
createdAt: event.createdAt,
kind: event.kind,
tags: event.tags,
content: 'response:${jsonEncode({'channel_id': dmId, 'created': true})}',
sig: event.sig,
);
}
}
void main() {
testWidgets('Siri quick send posts in the Bestie DM', (tester) async {
const channel = MethodChannel('buzz/quick_send');
final platformCalls = <String>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
call,
) async {
platformCalls.add(call.method);
return null;
});
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
channel,
null,
),
);
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
final owner = nostr.Keys.generate(), bestie = nostr.Keys.generate();
final relay = _Relay(owner);
String? chosenBestie;
await tester.pumpWidget(
ProviderScope(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
relayConfigProvider.overrideWith(
() => _Config(
RelayConfig(baseUrl: 'https://relay.test', nsec: owner.nsec),
),
),
relaySessionProvider.overrideWith(() => relay),
defaultAgentProvider.overrideWith(
(ref) => Stream.value(chosenBestie),
),
channelsProvider.overrideWith(_EmptyChannels.new),
appLifecycleProvider.overrideWith(_Lifecycle.new),
],
child: MaterialApp(
theme: AppTheme.light(),
home: const QuickSendHost(),
),
),
);
await tester.pumpAndSettle();
expect(platformCalls, ['ready'], reason: 'Siri can send once Home is up');
// Siri calls the host the way QuickSend.swift does and gets its reply.
Future<(Object?, PlatformException?)> siri(
String method, [
Object? arguments,
]) async {
Object? result;
PlatformException? failure;
var replied = false;
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
channel.name,
channel.codec.encodeMethodCall(MethodCall(method, arguments)),
(reply) {
try {
result = channel.codec.decodeEnvelope(reply!);
} on PlatformException catch (e) {
failure = e;
}
replied = true;
},
);
for (var i = 0; i < 100 && !replied; i++) {
await tester.pump(const Duration(milliseconds: 50));
}
expect(replied, isTrue, reason: '$method never answered');
return (result, failure);
}
final container = ProviderScope.containerOf(
tester.element(find.byType(QuickSendHost)),
);
container.read(relaySessionProvider);
relay.connect();
await tester.pump();
final (_, noBestie) = await siri('bestie');
expect(noBestie?.code, 'failed');
expect(noBestie?.message, 'Choose a Bestie in Buzz first.');
chosenBestie = bestie.public;
container.invalidate(defaultAgentProvider);
await tester.pump();
final (named, _) = await siri('bestie');
final scope = (named! as Map)['scope'];
expect(named, {'pubkey': bestie.public, 'scope': scope});
// A Bestie looked up before a community switch can't send here.
final (_, switched) = await siri('send', {
'text': 'Remind me to call Sam',
'bestie': bestie.public,
'scope': 'https://other.test $scope',
});
expect(switched?.message, contains('switched communities'));
final (_, blank) = await siri('send', {
'text': ' \n ',
'bestie': bestie.public,
'scope': scope,
});
expect(blank?.code, 'failed');
expect(blank?.message, 'Say a message.');
expect(relay.published, isEmpty);
// Buzz sat in the background long enough for its socket to close.
(container.read(appLifecycleProvider.notifier) as _Lifecycle).background();
relay.state = const SessionState(status: SessionStatus.disconnected);
final pausesBefore = relay.pauses;
// Its catch-up used the write quota, so the first try is turned away.
relay.rateLimitNextMessage = true;
await tester.pumpAndSettle();
final (_, failure) = await siri('send', {
'text': ' Remind me to call Sam ',
'bestie': bestie.public,
'scope': scope,
});
expect(failure, isNull);
expect(
relay.pauses,
pausesBefore + 1,
reason: 'The send hands the session back to its background pause',
);
final open = relay.published.singleWhere((e) => e.kind == 41010);
expect(open.pubkey, owner.public);
expect(open.tags, [
['p', bestie.public],
]);
final first = relay.published.singleWhere((e) => e.kind == 9);
expect(first.content, 'Remind me to call Sam');
expect(first.pubkey, owner.public);
expect(first.getTagValue('h'), _Relay.dmId);
expect(first.tags, contains(equals(['p', bestie.public])));
// A sent message leaves the DM's draft as it was.
final drafts = container.read(composeDraftsProvider.notifier);
drafts.save(
key: _Relay.dmId,
channelId: _Relay.dmId,
text: 'Half a @Sam',
mentions: [ComposeDraftMention(start: 7, end: 11, pubkey: 'a' * 64)],
);
// A second quick send goes to the same DM.
final (_, again) = await siri('send', {
'text': 'And buy milk',
'bestie': bestie.public,
'scope': scope,
});
expect(again, isNull);
final messages = relay.published.where((e) => e.kind == 9).toList();
expect(messages.map((e) => e.content), [
'Remind me to call Sam',
'And buy milk',
]);
expect(messages.map((e) => e.getTagValue('h')).toSet(), {_Relay.dmId});
expect(drafts.textFor(_Relay.dmId), 'Half a @Sam');
// When Buzz can't tell whether a send landed, the text stays in the DM's
// draft, after the person's own, and Siri says to check before resending.
relay.timeOutNextMessage = true;
final (_, unsure) = await siri('send', {
'text': 'Call back',
'bestie': bestie.public,
'scope': scope,
});
expect(
unsure?.message,
"Buzz isn't sure that sent. Check your Bestie DM before trying again.",
);
final kept = drafts.draftFor(_Relay.dmId)!;
expect(kept.text, 'Half a @Sam\n\nCall back');
expect(kept.mentions, [
ComposeDraftMention(start: 7, end: 11, pubkey: 'a' * 64),
]);
// A socket that drops just before the message goes out keeps it too.
relay.dropBeforeNextMessage = true;
final (_, dropped) = await siri('send', {
'text': 'Then Sam',
'bestie': bestie.public,
'scope': scope,
});
expect(dropped?.message, contains('Check your Bestie DM'));
expect(drafts.textFor(_Relay.dmId), 'Half a @Sam\n\nCall back\n\nThen Sam');
// Leaving Home, for example on sign-out, takes the handler with it.
await tester.pumpWidget(const SizedBox());
expect(platformCalls, ['ready', 'unready']);
// Let the sent messages' local animations finish.
await tester.pump(const Duration(seconds: 10));
});
}