Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 4 additions & 9 deletions mobile/lib/app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -417,14 +417,9 @@ class App extends HookConsumerWidget {
// notification reply, and no later frame may come to rebuild this.
ref.listen(notificationReplySenderProvider, (_, _) {});

void applyBadge(UnreadBadgeState state) {
if (state.highPriorityCount > 0) {
AppBadgePlus.updateBadge(state.highPriorityCount);
} else if (state.generalUnreadCount > 0) {
AppBadgePlus.updateBadge(1);
} else {
AppBadgePlus.updateBadge(0);
}
void applyBadge(UnreadBadge badge) {
final count = badge.platformCount;
if (count != null) AppBadgePlus.updateBadge(count);
}

useEffect(() {
Expand All @@ -436,7 +431,7 @@ class App extends HookConsumerWidget {
return null;
}, [ageSignalState]);
if (ageSignalState != AgeSignalState.restricted) {
ref.listen<UnreadBadgeState>(unreadBadgeProvider, (_, next) {
ref.listen<UnreadBadge>(unreadBadgeProvider, (_, next) {
applyBadge(next);
});
}
Expand Down
105 changes: 70 additions & 35 deletions mobile/lib/features/activity/activity_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -512,10 +512,11 @@ class ActivityNotifier extends AsyncNotifier<HomeFeedResponse> {
// Quiet agent messages (`audience: agents`) are coordination between
// agents and never become Activity items, even when they tag the reader.
final fetched = await _queryWithWebSocketFallback(session, filters);
final refill = await _refillPastQuiet(session, filters, fetched.events);
final events = [
for (final event in fetched)
for (final event in fetched.events)
if (!isQuietAgentMessage(event.tags)) event,
...await _refillPastQuiet(session, filters, fetched),
...refill.events,
];

bool isFromOther(NostrEvent e) =>
Expand Down Expand Up @@ -594,6 +595,7 @@ class ActivityNotifier extends AsyncNotifier<HomeFeedResponse> {
for (final i in items)
if (i.category == 'agent_activity') i,
],
complete: fetched.complete && refill.complete,
);
}

Expand All @@ -602,14 +604,16 @@ class ActivityNotifier extends AsyncNotifier<HomeFeedResponse> {
/// own window from the batched result (the bridge concatenates every
/// filter's newest `limit` matches), then pages past a window that lost
/// items to the quiet filter, a few pages at most, refilling only up to the
/// original limit. Returns the non-quiet events found on those pages.
Future<List<NostrEvent>> _refillPastQuiet(
/// original limit. Returns the non-quiet events found on those pages, and
/// whether every page read succeeded.
Future<({List<NostrEvent> events, bool complete})> _refillPastQuiet(
RelaySessionNotifier session,
List<NostrFilter> filters,
List<NostrEvent> fetched,
) async {
const maxPages = 3;
final found = <NostrEvent>[];
var complete = true;
for (final filter in filters) {
final seen = <String>{};
// Only the retained window is marked seen: matches past the cap came
Expand All @@ -634,17 +638,17 @@ class ActivityNotifier extends AsyncNotifier<HomeFeedResponse> {
// The relay's composite cursor, so events sharing the boundary
// second are not skipped.
final last = page.last;
page = window(
await _queryWithWebSocketFallback(session, [
NostrFilter(
kinds: filter.kinds,
tags: filter.tags,
limit: filter.limit,
until: last.createdAt,
extensions: {'before_id': last.id},
),
]),
);
final next = await _queryWithWebSocketFallback(session, [
NostrFilter(
kinds: filter.kinds,
tags: filter.tags,
limit: filter.limit,
until: last.createdAt,
extensions: {'before_id': last.id},
),
]);
complete = complete && next.complete;
page = window(next.events);
final kept = page
.where((e) => !isQuietAgentMessage(e.tags))
.take(filter.limit - visible)
Expand All @@ -653,7 +657,7 @@ class ActivityNotifier extends AsyncNotifier<HomeFeedResponse> {
visible += kept.length;
}
}
return found;
return (events: found, complete: complete);
}

/// Newest first, ties by ascending id: the relay's history order.
Expand All @@ -676,12 +680,15 @@ class ActivityNotifier extends AsyncNotifier<HomeFeedResponse> {
return true;
}

Future<List<NostrEvent>> _queryWithWebSocketFallback(
/// The events for [filters], and whether every filter was read. A filter
/// whose HTTP and websocket reads both fail contributes no events.
Future<({List<NostrEvent> events, bool complete})>
_queryWithWebSocketFallback(
RelaySessionNotifier session,
List<NostrFilter> filters,
) async {
try {
return await session.queryRelay(filters);
return (events: await session.queryRelay(filters), complete: true);
} catch (error) {
debugPrint(
'[ActivityNotifier] batched history query failed; '
Expand All @@ -691,6 +698,7 @@ class ActivityNotifier extends AsyncNotifier<HomeFeedResponse> {

const fallbackConcurrency = 4;
final events = <NostrEvent>[];
var complete = true;
for (var start = 0; start < filters.length; start += fallbackConcurrency) {
final end = start + fallbackConcurrency < filters.length
? start + fallbackConcurrency
Expand All @@ -700,6 +708,7 @@ class ActivityNotifier extends AsyncNotifier<HomeFeedResponse> {
try {
return await session.fetchHistory(filter);
} catch (_) {
complete = false;
return const <NostrEvent>[];
}
}),
Expand All @@ -708,7 +717,7 @@ class ActivityNotifier extends AsyncNotifier<HomeFeedResponse> {
events.addAll(result);
}
}
return events;
return (events: events, complete: complete);
}

FeedItem _feedItem(NostrEvent event, {required String category}) {
Expand Down Expand Up @@ -746,24 +755,20 @@ final activityProvider =
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;
/// Activity items for the DM messages, mentions and eligible thread replies
/// the channel list received. Channel discovery already catches up and
/// subscribes to joined channels, so Activity, the bell and the icon have
/// these even when a history read fails, lags or misses them, and no extra
/// subscription or read is needed. They always belong to the current
/// community: the channel list resets when it changes.
final observedActivityItemsProvider = Provider<List<FeedItem>>((ref) {
final channels =
ref.watch(channelsProvider).asData?.value ?? const <Channel>[];
final dmChannelIds = {
for (final channel in channels)
if (channel.isDm) channel.id,
};
final myPk = ref.watch(myPubkeyProvider);
// Channel discovery already catches up and subscribes to eligible replies.
// Keep that one source of truth for the dots and their Activity destination,
// rather than opening another set of channel subscriptions here.
final byId = <String, FeedItem>{
return [
for (final event
in ref.read(channelsProvider.notifier).observedThreadReplies(channels))
event.id: FeedItem(
in ref.read(channelsProvider.notifier).observedActivityEvents(channels))
FeedItem(
id: event.id,
kind: event.kind,
pubkey: event.pubkey,
Expand All @@ -776,8 +781,38 @@ final inboxItemsProvider = Provider<List<InboxItem>>((ref) {
? 'mention'
: 'activity',
),
];
});

/// 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;
final channelsNotifier = ref.read(channelsProvider.notifier);
final byId = <String, FeedItem>{
for (final item in ref.watch(observedActivityItemsProvider)) item.id: item,
// The addressed feed owns category precedence for overlapping events.
for (final item in feed?.all ?? const <FeedItem>[]) item.id: item,
// The channel list applies live deletions; the feed does not see them.
for (final item in feed?.all ?? const <FeedItem>[])
if (!channelsNotifier.isUnreadDeleted(item.id, channelId: item.channelId))
item.id: item,
};
return buildInboxItems(byId.values, isDmChannel: dmChannelIds.contains);
return _inboxRows(ref, byId.values);
});

/// Inbox rows for only the events the channel list received. The icon reads
/// these while the feed loads, because a loading feed can still hold the
/// previous community's rows.
final observedInboxItemsProvider = Provider<List<InboxItem>>(
(ref) => _inboxRows(ref, ref.watch(observedActivityItemsProvider)),
);

List<InboxItem> _inboxRows(Ref ref, Iterable<FeedItem> items) {
final channels =
ref.watch(channelsProvider).asData?.value ?? const <Channel>[];
final dmChannelIds = {
for (final channel in channels)
if (channel.isDm) channel.id,
};
return buildInboxItems(items, isDmChannel: dmChannelIds.contains);
}
4 changes: 4 additions & 0 deletions mobile/lib/features/activity/feed_item.dart
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,15 @@ class HomeFeedResponse {
final List<FeedItem> activity;
final List<FeedItem> agentActivity;

/// False when a source failed to load, so the feed may be missing items.
final bool complete;

HomeFeedResponse({
required this.mentions,
required this.needsAction,
required this.activity,
required this.agentActivity,
this.complete = true,
});

factory HomeFeedResponse.fromJson(Map<String, dynamic> json) {
Expand Down
39 changes: 34 additions & 5 deletions mobile/lib/features/activity/inbox_unread_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../../shared/read_state/read_state_provider.dart';
import 'activity_provider.dart';
import 'inbox_item.dart';
import 'inbox_local_state_provider.dart';
import 'inbox_read_state.dart';

/// The bell reflects the same unread rows shown by the Activity inbox.
final inboxHasUnreadProvider = Provider<bool>((ref) {
/// Whether Activity has unread rows, or read state has not loaded yet.
enum InboxUnread { pending, read, unread }

/// The shared unread rule for the Activity bell and app icon badge.
final inboxUnreadProvider = Provider<InboxUnread>((ref) {
final items = ref.watch(inboxItemsProvider);
final readState = ref.watch(readStateProvider);
final localState = ref.watch(inboxLocalStateProvider);
if (!readState.isReady) return false;
if (!readState.isReady) return InboxUnread.pending;
// A mark any device has read past is stale: remove it, not just ignore it.
final stale = [
for (final item in items)
Expand All @@ -28,7 +32,26 @@ final inboxHasUnreadProvider = Provider<bool>((ref) {
() => ref.read(inboxLocalStateProvider.notifier).clearUnread(stale),
);
}
return items.any(
return _inboxUnread(items, readState, localState);
});

/// [inboxUnreadProvider]'s rule over only the events the channel list
/// received, which always belong to the current community. The icon uses it
/// while the Activity feed loads.
final observedInboxUnreadProvider = Provider<InboxUnread>((ref) {
final items = ref.watch(observedInboxItemsProvider);
final readState = ref.watch(readStateProvider);
final localState = ref.watch(inboxLocalStateProvider);
if (!readState.isReady) return InboxUnread.pending;
return _inboxUnread(items, readState, localState);
});

InboxUnread _inboxUnread(
List<InboxItem> items,
ReadStateState readState,
InboxLocalState localState,
) {
final anyUnread = items.any(
(item) => !isInboxItemDone(
item,
markerOf: readState.effectiveTimestamp,
Expand All @@ -37,4 +60,10 @@ final inboxHasUnreadProvider = Provider<bool>((ref) {
localDoneSet: localState.doneIds,
),
);
});
return anyUnread ? InboxUnread.unread : InboxUnread.read;
}

/// The bell reflects unread Activity rows; pending read state shows no dot.
final inboxHasUnreadProvider = Provider<bool>(
(ref) => ref.watch(inboxUnreadProvider) == InboxUnread.unread,
);
27 changes: 16 additions & 11 deletions mobile/lib/features/channels/channel_directory.dart
Original file line number Diff line number Diff line change
Expand Up @@ -708,11 +708,12 @@ extension _ObservedUnreadRecording on ChannelsNotifier {
channelType: channel.channelType,
isThreadedReply: isThreadedReply,
isBroadcast: isBroadcast,
// Activity lists the thread replies that earn attention, including
// ones also sent to the channel, which earn it only here.
threadReply:
(isThreadedReply || (isBroadcast && isHighPriority)) &&
!channel.isDm
// Activity lists DM messages, mentions and the thread replies that
// earn attention, including replies also sent to the channel, which
// earn it only here. Ordinary channel traffic and quiet backlog
// markers stay out.
activityEvent:
!countQuiet && (channel.isDm || isThreadedReply || isHighPriority)
? event
: null,
),
Expand Down Expand Up @@ -740,16 +741,20 @@ extension ChannelDirectoryForgetting on ChannelsNotifier {
}

/// Activity projection of the channel unread registry.
extension ObservedThreadActivity on ChannelsNotifier {
/// The same eligible replies that supply channel attention dots. Consumers
/// watch [channelsProvider] for changes; this does not fetch extra history.
Iterable<NostrEvent> observedThreadReplies(Iterable<Channel> channels) sync* {
extension ObservedActivity on ChannelsNotifier {
/// The received DM messages, mentions and thread replies that also supply
/// channel unread state. Activity lists them even when its own history read
/// fails or misses them. Consumers watch [channelsProvider] for changes;
/// this does not fetch extra history.
Iterable<NostrEvent> observedActivityEvents(
Iterable<Channel> channels,
) sync* {
for (final channel in channels) {
if (!channel.isMember || channel.isArchived || channel.isDm) continue;
if (!channel.isMember || channel.isArchived) continue;
for (final observed
in _observedUnreadEventsByChannel[channel.id]?.values ??
const <ObservedUnreadEvent>[]) {
if (observed.threadReply case final reply?) yield reply;
if (observed.activityEvent case final event?) yield event;
}
}
}
Expand Down
10 changes: 10 additions & 0 deletions mobile/lib/features/channels/channel_unread_deletions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,13 @@ extension _UnreadDeletions on ChannelsNotifier {
);
}
}

/// Deletion evidence for readers outside the notifier.
extension UnreadDeletionLookup on ChannelsNotifier {
/// Whether relay deletion evidence removed [eventId] in [channelId].
/// Activity drops these rows: its feed holds no deletions of its own.
bool isUnreadDeleted(String eventId, {String? channelId}) =>
_unscopedUnreadDeletedIds.contains(eventId) ||
(channelId != null &&
_unreadDeletedIdsByChannel[channelId]?.contains(eventId) == true);
}
Loading
Loading