Files
buzz/mobile/lib/features/channels/send_message_provider.dart
Tom Brow 3689241672 feat(mobile): reply to a message from its iOS notification (#9439)
On iOS, a notification that shows a channel or DM message now offers
**Reply**. The user types a reply in the notification and sends it
without opening the app.

- The reply goes in a subthread under the notified message (its thread
root is the message's own root, or the message itself when top-level). A
Solo chat takes no thread replies, so there it goes at the chat's top
level.
- It always mentions the notified message's sender, so the person or
agent being answered is notified. Typed `@name` text stays plain, since
a notification has no mention autocomplete.
- It is sent by the app's own send path. iOS starts the Flutter engine
when it wakes the app in the background, and the reply reopens the relay
connection (closed after the background grace period), waiting a bounded
time for it before sending.
- A sent reply marks the conversation read **up to the notified
message** (newer messages stay unread) and clears that notification and
earlier ones from the same conversation.
- An unsent reply (offline, relay error, timeout, a channel the user
isn't in) keeps the typed text as a draft, after any draft already
there, and shows a "Reply not sent" notification that opens the
conversation.

For now only notifications from the community selected in the app offer
Reply: replying must not switch communities, and the app can only reach
the selected one. Forum posts and fallback notifications that show no
message offer none. The design and the options considered are in
`docs/adr/0004-notification-reply.md`.

### Before / after

Long-pressing a message notification (synthetic names and text). Before
has no reply field (captured by sending the notification without its new
reply category, which is how main presents it); after shows one with
Send.

| Before | After |
| --- | --- |
|
![before](https://raw.githubusercontent.com/block/buzz/df800599173cf3436af4d2c738447396a632fac7/pr-9439--before.png)
|
![after](https://raw.githubusercontent.com/block/buzz/df800599173cf3436af4d2c738447396a632fac7/pr-9439--after.png)
|

### Demo

With the app backgrounded past the relay grace period, replying from the
notification lands the reply in a subthread under the message:


https://github.com/user-attachments/assets/37df7e28-aa46-4521-938e-8af5faa77b83

### Regressions

Nothing existing changes unless the user taps Reply. Notifications gain
a category and a small reply context in `userInfo`; tapping a
notification still opens the conversation as before. The relay reconnect
only happens for a pending reply and then falls back to the normal
background disconnect, so idle background behavior and network use are
unchanged. Reply failures end in a draft and a "Reply not sent"
notification rather than touching other state.

### Validation

- End to end on an iOS 27 simulator against a real community: with the
app backgrounded past the relay grace period, replied from the
notification; the reply appeared in a subthread under the message,
mentioning its sender. The demo above was recorded before the review
fixes (session hold, community fence, origin-community drafts, composer
draft sync); the same run was repeated on the current head, 9b9c8b0, and
the reply again appeared in the subthread with no "Reply not sent"
notification.
- Human testing is waived for this repo's mobile client; the simulator
run above replaces it. Not yet exercised on a physical device or on a
cold launch (app not running).
- Added tests: a Dart journey covering top-level, in-thread and Solo
replies, another community (draft kept in that community), a failed
send, a channel the user isn't in (draft appended), a reply arriving
while running, an unreachable relay, and a community switch while
connecting (not sent, draft kept in the reply's community); a
relay-session test that a background-work hold keeps the grace
disconnect off, including one already waiting on cleanup, until released
or its limit; a composer step showing a draft appended elsewhere appears
in the mounted composer and survives its next edit; a relay-session test
for reconnecting a paused session and timing out (fails without the
fix); Swift tests for reply context encoding, NIP-10 root parsing
aligned with the app, and request validation.
- `relay_session.dart` was at its 1200-line cap, so the background
connect lives in a new part file and three existing test hooks moved
unchanged into another.
- Full `mobile-test`, `mobile-check` and BuzzPushKit `swift test` pass.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-18 16:15:28 +00:00

298 lines
11 KiB
Dart

import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../shared/mentions/mention_tags.dart';
import '../../shared/relay/relay.dart';
import '../channels/channel_management_provider.dart';
import '../../shared/profile/user_cache_provider.dart';
import '../../shared/profile/user_profile.dart';
import 'channel.dart';
import 'me/me_messages_provider.dart';
import 'channel_messages_provider.dart';
import 'message_mention_pubkeys.dart';
import 'local_message_send_animation_provider.dart';
/// Sends messages by signing an event with the user's nsec and publishing it
/// over the relay's NIP-42-authenticated WebSocket session.
class SendMessage {
final SignedEventRelay _signedEventRelay;
final Future<List<ChannelMember>> Function(String channelId) _fetchMembers;
final Map<String, UserProfile> Function() _readUserCache;
final void Function(String channelId, NostrEvent event) _addLocalMessage;
final void Function(String channelId, String eventId)
_markLocalMessageForAnimation;
final void Function(String channelId, String eventId) _completeLocalMessage;
final void Function(String channelId, String eventId) _removeLocalMessage;
final bool Function()? _isDeliveryValid;
SendMessage({
required SignedEventRelay signedEventRelay,
required Future<List<ChannelMember>> Function(String channelId)
fetchMembers,
required Map<String, UserProfile> Function() readUserCache,
required void Function(String channelId, NostrEvent event) addLocalMessage,
void Function(String channelId, String eventId)?
markLocalMessageForAnimation,
required void Function(String channelId, String eventId)
completeLocalMessage,
required void Function(String channelId, String eventId) removeLocalMessage,
bool Function()? isDeliveryValid,
}) : _signedEventRelay = signedEventRelay,
_fetchMembers = fetchMembers,
_readUserCache = readUserCache,
_addLocalMessage = addLocalMessage,
_markLocalMessageForAnimation =
markLocalMessageForAnimation ?? ((_, _) {}),
_completeLocalMessage = completeLocalMessage,
_removeLocalMessage = removeLocalMessage,
_isDeliveryValid = isDeliveryValid;
/// Send a text message to a channel.
///
/// For thread replies, pass [parentEventId] and optionally [rootEventId].
/// If [rootEventId] is null it defaults to [parentEventId] (direct reply to
/// thread head). Tags are built to match the desktop's `buildReplyTags`
/// convention with `root` / `reply` markers. Pass [mediaTags] to append
/// relay-validated `imeta` tags and NIP-30 `emoji` tags. [mayPublish] is
/// asked after every wait, right before the event is signed and published;
/// when it says no, nothing is published and this throws.
Future<void> call({
required String channelId,
required String content,
String? parentEventId,
String? rootEventId,
List<String>? mentionPubkeys,
Channel? channel,
List<List<String>> mediaTags = const [],
Future<bool> Function()? mayPublish,
}) async {
_ensureDeliveryValid();
// Use explicitly passed pubkeys, or resolve @mentions against
// channel members to avoid matching the wrong user.
final explicitMentions =
mentionPubkeys ?? await _resolveMentions(content, channelId);
final authorPubkey = _signedEventRelay.pubkey;
final dmRecipientPubkeys = channel?.isDm == true
? await _fetchDmRecipientPubkeys(channelId, channel!, authorPubkey)
: null;
final resolvedMentions = dmRecipientPubkeys != null
? messageMentionPubkeys(
channel: channel!,
senderPubkey: authorPubkey,
explicitMentions: explicitMentions,
dmRecipientPubkeys: dmRecipientPubkeys,
)
: explicitMentions;
// Normalize mentions: lowercase, deduplicate, exclude self (matching
// the desktop's normalizeMentionPubkeys).
final selfLower = authorPubkey?.toLowerCase();
final seenMentions = <String>{?selfLower};
final normalizedMentions = <String>[
for (final pk in resolvedMentions)
if (seenMentions.add(pk.toLowerCase())) pk,
];
// Two-field `mention` tags are references; they go through the same
// writer as recipients so a bad key rejects the message.
bool isReference(List<String> tag) =>
tag.length == 2 && tag[0] == 'mention';
final references = [
for (final tag in mediaTags)
if (isReference(tag)) tag[1],
];
final mentionTags = writeMentionTags(
recipients: normalizedMentions,
references: references,
members: normalizedMentions.isEmpty
? const {}
: await _recipientMembers(channelId, dmRecipientPubkeys, selfLower),
);
final tags = <List<String>>[
['h', channelId],
if (parentEventId != null) ..._buildReplyTags(parentEventId, rootEventId),
...mentionTags,
for (final tag in mediaTags)
if (!isReference(tag)) tag,
];
_ensureDeliveryValid();
NostrEvent? localMessage;
try {
await _signedEventRelay.submit(
kind: EventKind.streamMessage,
content: content,
tags: tags,
onSigned: (event) {
localMessage = event;
_markLocalMessageForAnimation(channelId, event.id);
_addLocalMessage(channelId, event);
},
mayPublish: mayPublish,
);
final event = localMessage;
if (event != null) _completeLocalMessage(channelId, event.id);
} catch (_) {
final event = localMessage;
if (event != null) _removeLocalMessage(channelId, event.id);
rethrow;
}
}
/// Resolve every identity that is actually a current member of this DM.
///
/// Membership is authoritative for delivery. The channel metadata's `p`
/// tags can lag membership changes, so they are only used when the membership
/// snapshot is unavailable.
Future<Set<String>> _fetchDmRecipientPubkeys(
String channelId,
Channel channel,
String? authorPubkey,
) async {
List<ChannelMember>? members;
try {
members = await _fetchMembers(channelId);
} catch (_) {
// Fall back to metadata below so an unavailable membership query does
// not block ordinary DM sends.
}
final author = authorPubkey?.toLowerCase();
return {
for (final participant in dmParticipantPubkeys(channel, members))
if (participant.trim().isNotEmpty &&
participant.toLowerCase() != author)
participant.toLowerCase(),
};
}
/// Keys that can be recipients: DM participants, or the channel's current
/// members. The sender always counts as a member.
Future<Set<String>> _recipientMembers(
String channelId,
Set<String>? dmRecipientPubkeys,
String? self,
) async {
final members =
dmRecipientPubkeys ??
{
for (final member in await _fetchMembers(channelId))
member.pubkey.toLowerCase(),
};
return {...members, ?self};
}
void _ensureDeliveryValid() {
if (_isDeliveryValid?.call() == false) {
throw StateError(
'Message delivery cancelled because the active community changed',
);
}
}
/// Resolve @mentions to pubkeys, scoped to channel members.
///
/// Fetches channel members from the relay and matches @names only
/// against members of that channel. Falls back to the full user cache
/// if the member fetch fails.
Future<List<String>> _resolveMentions(
String content,
String channelId,
) async {
final mentionPattern = RegExp(r'@(\w+)');
final matches = mentionPattern.allMatches(content);
if (matches.isEmpty) return const [];
// Try to get channel member pubkeys for scoped resolution.
Set<String>? memberPubkeys;
try {
final members = await _fetchMembers(channelId);
memberPubkeys = {for (final m in members) m.pubkey.toLowerCase()};
} catch (_) {
// Non-fatal — fall through to unscoped cache lookup.
}
final cache = _readUserCache();
final pubkeys = <String>{};
for (final match in matches) {
final name = match.group(1)?.toLowerCase();
if (name == null || name.isEmpty) continue;
for (final profile in cache.values) {
final displayName = profile.displayName?.toLowerCase();
if (displayName == null) continue;
// Match against full display name or first word.
final firstName = displayName.split(RegExp(r'\s+')).first;
if (displayName != name && firstName != name) continue;
// If we have channel members, only match members of this channel.
if (memberPubkeys != null &&
!memberPubkeys.contains(profile.pubkey.toLowerCase())) {
continue;
}
pubkeys.add(profile.pubkey);
break;
}
}
return pubkeys.toList();
}
/// Build `e`-tags for a thread reply, matching the desktop convention:
/// - Direct reply to thread head: `["e", id, "", "reply"]`
/// - Nested reply: `["e", rootId, "", "root"]` + `["e", parentId, "", "reply"]`
static List<List<String>> _buildReplyTags(
String parentEventId,
String? rootEventId,
) {
final root = rootEventId ?? parentEventId;
if (parentEventId == root) {
return [
['e', root, '', 'reply'],
];
}
return [
['e', root, '', 'root'],
['e', parentEventId, '', 'reply'],
];
}
}
final sendMessageProvider = Provider<SendMessage>((ref) => _sender(ref));
/// Shares signing and delivery with channels, with Me's flat optimistic reader.
final meSendMessageProvider = Provider<SendMessage>(
(ref) => _sender(ref, personal: true),
);
SendMessage _sender(Ref ref, {bool personal = false}) {
final messages = personal ? meMessagesProvider : channelMessagesProvider;
final config = ref.watch(relayConfigProvider);
return SendMessage(
signedEventRelay: SignedEventRelay(
session: ref.read(relaySessionProvider.notifier),
nsec: config.nsec,
),
fetchMembers: (channelId) =>
ref.read(channelMembersProvider(channelId).future),
readUserCache: () => ref.read(userCacheProvider),
addLocalMessage: (channelId, event) =>
ref.read(messages(channelId).notifier).addLocalMessage(event),
markLocalMessageForAnimation: (channelId, eventId) => ref
.read(localMessageSendAnimationProvider(channelId).notifier)
.mark(eventId),
completeLocalMessage: (channelId, eventId) =>
ref.read(messages(channelId).notifier).completeLocalMessage(eventId),
removeLocalMessage: (channelId, eventId) =>
ref.read(messages(channelId).notifier).removeLocalMessage(eventId),
isDeliveryValid: () {
final currentConfig = ref.read(relayConfigProvider);
return currentConfig.baseUrl == config.baseUrl &&
currentConfig.nsec == config.nsec;
},
);
}