Files
buzz/mobile/lib/features/channels/send_message_provider.dart
Tom Brow 03336d0872 fix(mobile): only say "Community changed" when the community changed (#9156)
On mobile, a text send that failed for almost any reason showed **"Not
sent. Community changed."** The composer caught every `StateError` as a
community switch, and relay failures such as a briefly disconnected
socket (`RelaySession.publish` throws "Relay session is not connected")
are also `StateError`s. So a reconnect blip during a send told the user
they had switched communities when they hadn't.

The community-switch guards in message, forum and channel-action
delivery now throw a dedicated `ActiveCommunityChangedError`, and an
unconnected publish throws `RelayNotConnectedError`. Both still extend
`StateError`, so every existing `on StateError` caller behaves as
before. The composer now reports:

| Failure | Message |
| --- | --- |
| Active community changed mid-send | Not sent. Community changed. |
| Relay socket not connected | Not sent. No connection. |
| Relay never acknowledged the event (ack timeout) | Not confirmed. The
relay didn't respond. |
| A relay request timed out before the event was published (e.g. a
roster lookup) | Not sent. The relay didn't respond. |
| Connection lost after the event was sent, before its acknowledgement |
Not confirmed. Connection lost. |
| Relay rejected the event, or anything else | Not sent: *relay reason
or error text* |

The two "Not confirmed" cases may still have been accepted by the relay,
so they avoid a definite "Not sent" that would invite a duplicate
resend. Pending publishes rejected by a disconnect or backgrounding now
complete with a typed `RelayAckLostError` instead of a generic
exception, and an unacknowledged publish times out with
`RelayAckTimeoutError` (still a `TimeoutException`) so it can be told
apart from earlier timeouts.

The draft is restored in every case, as before.

### Validation

- Added [composer widget
tests](https://github.com/block/buzz/pull/9156/files#diff-101740841aadcb902d0717f3909debe16073c672e73be74a5b908bf11dfc8782)
for each non-community failure (disconnect, timeout before publishing,
ack timeout, connection lost before acknowledgement, relay rejection,
other `StateError`), checking the snackbar text, that the draft is
restored, and whether the message EVENT was sent. The disconnect,
timeout and connection-lost cases run through the real relay session (a
pending publish rejected by backgrounding, a history request that times
out before any message EVENT). The existing community-switch journey
goes through the real channel-action guard.
- Simulator (iPhone 17 Pro, debug build of this branch signed in to a
test community): opened a channel and sent a message; it was delivered
and the composer cleared normally. Limitation: the error paths
themselves were exercised only by widget tests, since the simulator
shares the Mac's network and I couldn't drop the relay connection for it
alone.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

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-19 12:02:38 -07:00

305 lines
11 KiB
Dart

import 'dart:async';
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 [],
FutureOr<void> Function(NostrEvent)? beforePublish,
void Function()? validateDelivery,
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) async {
await beforePublish?.call(event);
_ensureDeliveryValid();
validateDelivery?.call();
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 ActiveCommunityChangedError(
'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;
},
);
}