Files
b30f1f6129 Polish mobile profiles, DMs, and sheets (#5401)
## Summary
- add poster-first, tap-to-toggle animated avatars on profile surfaces
while preserving transparent/static behavior elsewhere
- align mobile DM headers, membership actions, and invisible agent
recipient addressing with established desktop semantics
- polish titled sheets and status editing, preserve native iOS sheet
corners, and batch relay reads to improve review-build responsiveness

## Snapshots

<table>
  <tr>
    <th>Profile avatar</th>
    <th>Agent DM header and composer</th>
  </tr>
  <tr>
<td><img
src="https://raw.githubusercontent.com/block/buzz/e8de7495451dbe1a393ab43c5e204ca7425f2ba5/pr-5401--profile-avatar.png"
width="360" alt="Mobile profile settings with animated avatar
surface"></td>
<td><img
src="https://raw.githubusercontent.com/block/buzz/e8de7495451dbe1a393ab43c5e204ca7425f2ba5/pr-5401--agent-dm.png"
width="360" alt="Agent direct message with masked presence and normal
composer"></td>
  </tr>
  <tr>
    <th>Members sheet</th>
    <th>Status editor</th>
  </tr>
  <tr>
<td><img
src="https://raw.githubusercontent.com/block/buzz/e8de7495451dbe1a393ab43c5e204ca7425f2ba5/pr-5401--members-sheet.png"
width="360" alt="Members bottom sheet with centered title and padded
content"></td>
<td><img
src="https://raw.githubusercontent.com/block/buzz/e8de7495451dbe1a393ab43c5e204ca7425f2ba5/pr-5401--status-sheet.png"
width="360" alt="Status editor bottom sheet with duration and quick
statuses"></td>
  </tr>
  <tr>
    <th colspan="2">Switch Community</th>
  </tr>
  <tr>
<td colspan="2" align="center"><img
src="https://raw.githubusercontent.com/block/buzz/e8de7495451dbe1a393ab43c5e204ca7425f2ba5/pr-5401--switch-community.png"
width="720" alt="Switch Community bottom sheet with centered title and
aligned Edit action"></td>
  </tr>
</table>

## Validation
- `just mobile-check`
- `just mobile-test` (1,283 tests)
- installed and reviewed isolated debug builds on iPhone and Pixel

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Signed-off-by: Princess Donut <b238ea756dee4d98afa5883fc7f1de61eeabe65bf700e3a5a5a80db5e42e2c2b@buzz.block.builderlab.xyz>
Signed-off-by: Kenny Lopez <klopez4212@gmail.com>
Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Princess Donut <b238ea756dee4d98afa5883fc7f1de61eeabe65bf700e3a5a5a80db5e42e2c2b@buzz.block.builderlab.xyz>
Co-authored-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Carl <c7ebe626f000404285d3686e1dc74cc07cc60a9754a150041ba132e14bd3e2ec@buzz.block.builderlab.xyz>
2026-08-13 20:16:04 -07:00

408 lines
12 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../shared/relay/relay.dart';
import '../channels/channel.dart';
import '../channels/channels_provider.dart';
import 'feed_item.dart';
import 'inbox_item.dart';
/// Builds the Activity inbox feed over the relay websocket.
///
/// Sources mirror desktop's Home inbox (`useHomeFeedQuery` + `get_feed`):
/// - mentions of me on user-visible channel kinds (also yields thread
/// replies, which the thread filter classifies from NIP-10 tags)
/// - workflow approvals / needs-action events addressed to me
/// - agent job lifecycle events addressed to me (kinds 43001-43006)
/// - recent DM messages from others (desktop surfaces DMs through p-tags;
/// mobile queries DM channels directly so untagged DM sends still appear)
class ActivityNotifier extends AsyncNotifier<HomeFeedResponse> {
static const _addressedKinds = [
1,
9,
40002,
43001,
43002,
43003,
43004,
43005,
43006,
45001,
45003,
46010,
46011,
46012,
];
void Function()? _unsubscribeAddressed;
void Function()? _unsubscribeDms;
Timer? _liveRefreshTimer;
Future<void>? _refreshInFlight;
int? _refreshGeneration;
bool _refreshQueued = false;
int _subscriptionGeneration = 0;
@override
Future<HomeFeedResponse> build() async {
ref.watch(relayConfigProvider);
final sessionState = ref.watch(relaySessionProvider);
// React to the DM channel set (loading → data, membership changes) so a
// cold start where channels resolve after the first fetch still surfaces
// DMs without a manual refresh.
ref.watch(channelsProvider.select(_dmChannelKey));
final generation = ++_subscriptionGeneration;
_clearLiveSubscriptions();
ref.onDispose(() {
_subscriptionGeneration += 1;
_clearLiveSubscriptions();
});
final response = await _fetch();
if (sessionState.status == SessionStatus.connected &&
generation == _subscriptionGeneration) {
unawaited(_subscribeLive(generation));
}
return response;
}
Future<void> _subscribeLive(int generation) async {
final myPk = ref.read(myPubkeyProvider);
if (myPk == null || generation != _subscriptionGeneration) return;
final session = ref.read(relaySessionProvider.notifier);
final since = DateTime.now().millisecondsSinceEpoch ~/ 1000 - 5;
try {
final unsubscribeAddressed = await session.subscribe(
NostrFilter(
kinds: _addressedKinds,
tags: {
'#p': [myPk],
},
since: since,
limit: 100,
),
(_) => _scheduleLiveRefresh(generation),
);
if (generation != _subscriptionGeneration) {
unsubscribeAddressed();
return;
}
_unsubscribeAddressed = unsubscribeAddressed;
final dmChannelIds = [
for (final channel
in ref.read(channelsProvider).asData?.value ?? const <Channel>[])
if (channel.isDm && channel.isMember) channel.id,
];
if (dmChannelIds.isEmpty) return;
final unsubscribeDms = await session.subscribe(
NostrFilter(
kinds: const [9],
tags: {'#h': dmChannelIds},
since: since,
limit: 100,
),
(_) => _scheduleLiveRefresh(generation),
);
if (generation != _subscriptionGeneration) {
unsubscribeDms();
return;
}
_unsubscribeDms = unsubscribeDms;
} catch (error) {
if (generation == _subscriptionGeneration) {
debugPrint('[ActivityNotifier] live subscription failed: $error');
}
}
}
void _scheduleLiveRefresh(int generation) {
if (generation != _subscriptionGeneration) return;
_liveRefreshTimer?.cancel();
_liveRefreshTimer = Timer(
const Duration(milliseconds: 50),
() => unawaited(_queueRefresh(generation)),
);
}
Future<void> _queueRefresh(int generation) {
if (generation != _subscriptionGeneration) return Future.value();
_refreshQueued = true;
final inFlight = _refreshInFlight;
if (_refreshGeneration == generation && inFlight != null) {
return inFlight;
}
_refreshGeneration = generation;
final future = _drainRefreshQueue(generation);
_refreshInFlight = future;
return future;
}
Future<void> _drainRefreshQueue(int generation) async {
try {
do {
_refreshQueued = false;
try {
final next = await _fetch();
if (generation != _subscriptionGeneration) return;
state = AsyncData(next);
} catch (error) {
if (generation != _subscriptionGeneration) return;
debugPrint(
'[ActivityNotifier] inbox refresh failed; retaining feed: $error',
);
}
} while (_refreshQueued && generation == _subscriptionGeneration);
} finally {
if (_refreshGeneration == generation) {
_refreshInFlight = null;
_refreshGeneration = null;
_refreshQueued = false;
}
}
}
void _clearLiveSubscriptions() {
_liveRefreshTimer?.cancel();
_liveRefreshTimer = null;
_refreshInFlight = null;
_refreshGeneration = null;
_refreshQueued = false;
_unsubscribeAddressed?.call();
_unsubscribeAddressed = null;
_unsubscribeDms?.call();
_unsubscribeDms = null;
}
/// Stable identity for the joined DM channel set: null while channels are
/// loading, otherwise the sorted member-DM ids. Keeps unrelated channel
/// updates from refetching the feed.
static String? _dmChannelKey(AsyncValue<List<Channel>> channels) {
final value = channels.asData?.value;
if (value == null) return null;
final ids = [
for (final channel in value)
if (channel.isDm && channel.isMember) channel.id,
]..sort();
return ids.join(',');
}
Future<HomeFeedResponse> _fetch() async {
final myPk = ref.read(myPubkeyProvider);
if (myPk == null) {
return HomeFeedResponse(
mentions: const [],
needsAction: const [],
activity: const [],
agentActivity: const [],
);
}
final session = ref.read(relaySessionProvider.notifier);
// DM channels come from the channel list; while it is still loading the
// DM source is skipped, and build() rebuilds when it resolves (see the
// channelsProvider watch above).
final dmChannelIds = [
for (final channel
in ref.read(channelsProvider).asData?.value ?? const <Channel>[])
if (channel.isDm && channel.isMember) channel.id,
];
final filters = <NostrFilter>[
// Mentions of me on user-visible channel content.
NostrFilter(
kinds: const [9, 40002, 1, 45001, 45003],
tags: {
'#p': [myPk],
},
limit: 50,
),
// Workflow approvals addressed to me.
NostrFilter(
kinds: const [46010, 46011, 46012],
tags: {
'#p': [myPk],
},
limit: 20,
),
// Agent job lifecycle events addressed to me.
NostrFilter(
kinds: const [43001, 43002, 43003, 43004, 43005, 43006],
tags: {
'#p': [myPk],
},
limit: 20,
),
// Recent DM traffic (filtered to other senders below).
if (dmChannelIds.isNotEmpty)
NostrFilter(kinds: const [9], tags: {'#h': dmChannelIds}, limit: 30),
];
// The HTTP bridge keeps each NIP-01 filter's independent limit while
// executing the batch with bounded server-side concurrency. One request
// here replaces the four simultaneous websocket history subscriptions that
// otherwise compete with channel and preference startup sync.
final events = await _queryWithWebSocketFallback(session, filters);
bool isFromOther(NostrEvent e) =>
e.pubkey.toLowerCase() != myPk.toLowerCase();
bool isAddressedToMe(NostrEvent event) => event.tags.any(
(tag) =>
tag.length > 1 &&
tag[0] == 'p' &&
tag[1].toLowerCase() == myPk.toLowerCase(),
);
const mentionKinds = {9, 40002, 1, 45001, 45003};
const needsActionKinds = {46010, 46011, 46012};
const agentActivityKinds = {43001, 43002, 43003, 43004, 43005, 43006};
final dmChannelIdSet = dmChannelIds.toSet();
// Dedupe across sources by event id, keeping the higher-priority
// category (needs_action > mention > agent_activity > activity).
final byId = <String, FeedItem>{};
void add(Iterable<NostrEvent> events, String category) {
for (final event in events) {
final existing = byId[event.id];
if (existing != null &&
categoryPriority(existing.category) <= categoryPriority(category)) {
continue;
}
byId[event.id] = _feedItem(event, category: category);
}
}
add(
events.where(
(event) =>
needsActionKinds.contains(event.kind) && isAddressedToMe(event),
),
'needs_action',
);
add(
events.where(
(event) =>
mentionKinds.contains(event.kind) &&
isAddressedToMe(event) &&
isFromOther(event),
),
'mention',
);
add(
events.where(
(event) =>
agentActivityKinds.contains(event.kind) && isAddressedToMe(event),
),
'agent_activity',
);
add(
events.where(
(event) =>
event.kind == 9 &&
dmChannelIdSet.contains(event.channelId) &&
isFromOther(event),
),
'activity',
);
final items = byId.values.toList()
..sort((a, b) => b.createdAt.compareTo(a.createdAt));
return HomeFeedResponse(
mentions: [
for (final i in items)
if (i.category == 'mention') i,
],
needsAction: [
for (final i in items)
if (i.category == 'needs_action') i,
],
activity: [
for (final i in items)
if (i.category == 'activity') i,
],
agentActivity: [
for (final i in items)
if (i.category == 'agent_activity') i,
],
);
}
Future<List<NostrEvent>> _queryWithWebSocketFallback(
RelaySessionNotifier session,
List<NostrFilter> filters,
) async {
try {
return await session.queryRelay(filters);
} catch (error) {
debugPrint(
'[ActivityNotifier] batched history query failed; '
'using bounded websocket fallback: $error',
);
}
const fallbackConcurrency = 4;
final events = <NostrEvent>[];
for (var start = 0; start < filters.length; start += fallbackConcurrency) {
final end = start + fallbackConcurrency < filters.length
? start + fallbackConcurrency
: filters.length;
final results = await Future.wait(
filters.sublist(start, end).map((filter) async {
try {
return await session.fetchHistory(filter);
} catch (_) {
return const <NostrEvent>[];
}
}),
);
for (final result in results) {
events.addAll(result);
}
}
return events;
}
FeedItem _feedItem(NostrEvent event, {required String category}) {
return FeedItem(
id: event.id,
kind: event.kind,
pubkey: event.pubkey,
content: event.content,
createdAt: event.createdAt,
channelId: event.channelId,
channelName: '',
tags: event.tags,
category: category,
);
}
Future<void> refresh() async {
await _queueRefresh(_subscriptionGeneration);
}
}
final activityProvider =
AsyncNotifierProvider<ActivityNotifier, HomeFeedResponse>(
ActivityNotifier.new,
);
/// Conversation-grouped inbox rows derived from the raw feed. DM messages
/// group by DM channel so one conversation renders as one row.
final inboxItemsProvider = Provider<List<InboxItem>>((ref) {
final feed = ref.watch(activityProvider).value;
if (feed == null) return const [];
final dmChannelIds = {
for (final channel
in ref.watch(channelsProvider).asData?.value ?? const <Channel>[])
if (channel.isDm) channel.id,
};
return buildInboxItems(feed.all, isDmChannel: dmChannelIds.contains);
});