mirror of
https://github.com/block/buzz.git
synced 2026-11-02 07:22:55 +00:00
## Summary Bring desktop Solo chats and project organization to mobile, with synced collapsible sections, shared unread highlights and tab badges, agent selection, shared search, native iOS creation sheets, and inline typing bubbles that transition into replies. Resolve Solo placement for every chat entry route, retain encrypted organization snapshots for offline reading, and let users resume or discard unfinished chat and project setup without deleting existing messages. ### Related issue Related: #6565; expandable agent transcripts remain separate work. ### Testing - Fresh Solo read state seeds each active chat from its captured initial last-message timestamp before exposing row/section/tab unread state. Baselines survive intervening channel updates and reset across identity/community boundaries while surviving read-state readiness changes. Regressions cover multiple chats, events before read-state readiness and during/after seeding, and identity changes; removing either the seed or the display gate fails them. - Chat completion reconciles a retained Solo-save journal even when placement is already confirmed. False/throwing cleanup regressions ensure the outer intent remains until reconciliation and only one placement is published. Typing terminal-close loops remain bounded; the retry budget resets after an uninterrupted eight-second health interval or transport reconnect. - Typing retry budgets reset after sustained recovery; invalid Solo updates retain cached rows with a retry warning that survives failed refreshes. Project names use the editors’ 120-grapheme limit, including emoji and combining characters. Regression coverage exercises repeated recovery, invalid live/refresh heads, and character-limit boundaries. - Rebased onto current main, preserving the newer Search controls, Huddle timeline filtering, and message-media layout. - Failed project journal writes reload storage before claiming recovery and reopen the entered name for retry. Typing subscription rejections are caught; terminal closures clear stale indicators and retry with a bounded backoff, canceled on disposal. Regression tests cover both false/throwing storage writes and initial/late subscription rejection. - Explicit ordinary destinations skip optional Solo lookup waits. Generic destinations perform one bounded lookup in the destination (search no longer duplicates it); an unavailable classification falls back to ordinary sending per the product owner's explicit choice. Positively identified Solo destinations use Solo providers. - Terminal Solo subscription closure preserves cached rows and exposes live-update Retry. Page coverage verifies warning visibility, usable rows during recovery, and a subsequent terminal close. Removing the warning or the immediate ordinary-route guard fails its regression. - Generic channel entries share an ordinary default when Solo classification is unavailable, per the requested product behavior. Known Solo placement takes precedence; callers can explicitly require unresolved placement to remain blocked. Bounded initial lookup preserves known Solo deep-link routing. - Dirty newest snapshots and offline-save warnings survive transport reconnects; Retry persists that same event even if the relay returns an older head. Community changes replace the service, and agent-directory reconnect refresh remains intact. - Pending-save discard reloads failed removals. Repeated reconnect testing confirms typing subscriptions are released on provider rebuild and disposal; removing the existing cleanup fails the regression. - Ordinary Home/create routes explicitly preserve private-channel sending during Solo failures; identified Solo sends use the Solo sender and explicit unresolved routes remain fail-closed. Solo unread replies beyond the initial 200-event page are loaded through the oldest-unread boundary. - Chat/project/agent cleanup reloads failed removals, retains same-process recovery, and protects replaced records. False/throw regressions verify retries do not duplicate creation or membership. Route, unread, and cleanup guard-removal mutations each fail their regression. - Ordinary channels, DMs, and forums remain sendable when optional Solo sync fails; explicit unresolved placement stays blocked. Controlled cache races retain the newest verified snapshot, keep usable chats visible, and retry offline persistence without stale writes. Both protection-removal regressions fail as expected. - Confirmed journal cleanup checks false/throwing removal and exact-record identity. Interrupted agent choices are visible immediately, identify the saved agent, and cover Resume/Later/Discard with accessible name/key-fallback controls. - Notification deep links preserve the contiguous history cursor; same-second messages infer the newest agent consistently. Failed offline-cache writes surface Retry, with false/throwing storage failures and offline restart covered. - Composite history cursors cover 350 same-second events plus older history; removing the ID cursor makes the regression fail. Agent changes now journal before granting access, with restart/failure and Resume/Later/Discard widget coverage. Signed malformed profiles remain isolated. - Native iOS avatar tests passed on the simulator: visible-row loading, three-request concurrency, streamed byte limits, response validation, downsampling/pixel limits, cancellation, and visible avatar updates. - Solo and Home share observed-event/read-marker logic. Widget coverage verifies unread rows, collapsed-section indicators, the tab badge before first Solo visit, message/thread reads, forced unread, and filtering archived/nonmember/unplaced chats. - Chat intent is saved before ownership and organization preflight; tests cover interrupted ownership lookup and a disconnect while the native creation form is open. - Mobile analysis, formatting, file-size checks, and full mobile tests passed at `1d4c41354`. - Project creation persists its encrypted name/UUID before connectivity checks or relay reads. Restart tests cover Resume/Later/Discard, scope isolation, stale-intent rejection, and lost acknowledgements. Removing the pre-network save makes all four production-flow regressions fail. - Regression coverage includes notification/Activity routing, inline replies, unknown-placement send protection, restart recovery/discard, and encrypted offline cache isolation/refresh. - Earlier feature build exercised on a physical iPhone with existing account/community data; review follow-ups have not been reinstalled on the device. UIKit agent-row accessibility checks passed on an iOS simulator. - Earlier cross-platform `just ci` stopped on the existing `buzz-acp` test `signals_cancel_startup_turn_and_pending_stdin_without_hanging` (process exit-code assertion); no Rust production changes are included in this PR. ### Remaining review limitation Agent discovery is bounded to 10 pages / 1,000 profiles with automatic retries disabled. Owner-scoped discovery remains open because the current relay ignores `#auth` filters; supporting that query requires a relay change. ### Snapshots Sample data, shared Flutter/Android surface. Native iOS uses platform sheets and controls. | Solo: projects and chats | New chat | Choose an agent | | --- | --- | --- | | <img src="https://raw.githubusercontent.com/block/buzz/d9b29aa079a3b9a88e8ed89b70df8d6af06fa41b/pr-8337--01-solo.png" width="240" alt="Solo with collapsible projects and chats" /> | <img src="https://raw.githubusercontent.com/block/buzz/d9b29aa079a3b9a88e8ed89b70df8d6af06fa41b/pr-8337--02-new-chat.png" width="240" alt="New chat form" /> | <img src="https://raw.githubusercontent.com/block/buzz/d9b29aa079a3b9a88e8ed89b70df8d6af06fa41b/pr-8337--03-agent-picker.png" width="240" alt="Agent selection list" /> | --------- Signed-off-by: kenny lopez <klopez4212@gmail.com> Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> Co-authored-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
294 lines
10 KiB
Dart
294 lines
10 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.
|
|
Future<void> call({
|
|
required String channelId,
|
|
required String content,
|
|
String? parentEventId,
|
|
String? rootEventId,
|
|
List<String>? mentionPubkeys,
|
|
Channel? channel,
|
|
List<List<String>> mediaTags = const [],
|
|
}) 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);
|
|
},
|
|
);
|
|
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;
|
|
},
|
|
);
|
|
}
|