Skip to content
Open
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
28 changes: 28 additions & 0 deletions mobile/lib/features/channels/channel_detail_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ import '../forum/forum_posts_view.dart';
import '../forum/forum_provider.dart';
import 'android_ime_lift.dart';
import 'channel.dart';
import 'channel_unread.dart';
import 'channel_actions_sheet.dart';
import 'channel_identity_names_provider.dart';
import 'channel_member_profile_actions.dart';
Expand Down Expand Up @@ -620,6 +621,33 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget {
});
}, [channel.id, readState.isReady, openReadActive, openReadTimestamp]);

// Row hints follow the same active visit as open-read. DMs, forums and
// Solo keep their own unread behavior.
final rowSeenActive =
openReadActive &&
!resolvedChannel.isDm &&
!resolvedChannel.isForum &&
!resolvedChannel.isSolo &&
!personalChat;
final observedRevision = ref.watch(
channelsProvider.select(
(_) => channelsNotifier.observedUnreadRevisionFor(channel.id),
),
);
useEffect(() {
if (!rowSeenActive || !readState.isReady) return null;
return deferReadStateUpdate(context, () {
final marks = channelRowSeenMarks(
channel.id,
channelsNotifier.observedUnreadEventsFor(channel.id),
ref.read(readStateProvider),
);
if (marks.isNotEmpty) {
ref.read(readStateProvider.notifier).markChannelRowSeen(marks);
}
});
}, [channel.id, rowSeenActive, readState.isReady, observedRevision]);

final headerMembers = ref.watch(
latestChannelMembersProvider(resolvedChannel.id),
);
Expand Down
15 changes: 15 additions & 0 deletions mobile/lib/features/channels/channel_directory.dart
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,21 @@ String _encodeRootIdSet(Set<String> values) => jsonEncode(values.toList());
/// ceiling enforced by `just file-size-check`. Private members stay reachable:
/// a part shares its parent's library.
extension _ObservedUnreadRecording on ChannelsNotifier {
/// Adds [event]'s thread to the in-memory interest sets; true when new.
/// Callers persist with [_writeThreadInterestStores], once per batch: each
/// write re-encodes both whole sets on the main thread.
bool _addSelfThreadInterest(NostrEvent event) {
final ref = event.threadReference;
final target = ref.rootId != null ? _participatedRootIds : _authoredRootIds;
return target.add(ref.rootId ?? event.id);
}

void _notifyUnreadReadinessChanged() {
final previous = _unreadReadinessChanged;
_unreadReadinessChanged = Completer<void>();
previous.complete();
}

bool _recordUnreadEvent(
Channel channel,
NostrEvent event,
Expand Down
51 changes: 43 additions & 8 deletions mobile/lib/features/channels/channel_unread.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import 'dart:math';

import '../../shared/read_state/read_state_format.dart';
import '../../shared/read_state/read_state_provider.dart';
import 'channel.dart';
import 'channels_provider.dart';
Expand Down Expand Up @@ -139,31 +142,63 @@ int _channelHighlights({
if (channelReadAt != null && latestObserved <= channelReadAt) return flags;
if (observedEvents == null) return flags;

final seenAt = separateAttention
? readState.contexts['seen:${channel.id}']
: null;
final applyRowMarks = separateAttention && !forced && !channel.isDm;
for (final event in observedEvents.values) {
final readAt = observedUnreadEventReadAt(
event,
channel.id,
readState.effectiveTimestamp,
);
if (readAt != null && event.createdAt <= readAt) continue;
final rowShowsEvent =
!applyRowMarks ||
!rowSawObservedUnreadEvent(event, channel.id, readState.contexts);
if (!separateAttention || channel.isDm || !event.attention) {
flags |= _unread;
if (separateAttention &&
(channel.isDm || seenAt == null || event.createdAt > seenAt)) {
flags |= _rowUnread;
}
if (separateAttention && rowShowsEvent) flags |= _rowUnread;
}
if (separateAttention && (channel.isDm || event.attention)) {
if (separateAttention &&
rowShowsEvent &&
(channel.isDm || event.attention)) {
flags |= _attention;
}
if (flags == decided) break;
}
return flags;
}

/// The marks earned by a visit. Attention uses per-message receipts so it
/// can light up the row even when it arrives later with an older timestamp.
Map<String, int> channelRowSeenMarks(
String channelId,
Map<String, ObservedUnreadEvent> events,
ReadStateState readState,
) {
final marks = <String, int>{};
var newest = 0;
var ordinary = false;
for (final event in events.values) {
final readAt = observedUnreadEventReadAt(
event,
channelId,
readState.effectiveTimestamp,
);
if (readAt != null && event.createdAt <= readAt) continue;
if (rowSawObservedUnreadEvent(event, channelId, readState.contexts)) {
continue;
}

newest = max(newest, event.createdAt);
if (event.channelCatchUp) {
ordinary = true;
} else {
marks[seenMessageContextKey(event.id)] = event.createdAt;
Comment on lines +194 to +195

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound locally retained attention receipts

For every attention event observed while a channel is open, this creates a unique seen:msg:<id> context, with no count-based eviction. These contexts accumulate in ReadStateManager._effectiveState; serialization filters old timestamps but never removes them from the live map, while every receipt within the 30-day horizon is rewritten into the journal. Sustained mention/reply traffic therefore makes memory use and each JSON persist grow continuously during a long-running session, so the receipt set needs live pruning or a hard capacity bound.

AGENTS.md reference: AGENTS.md:L249-L256

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Prune expired row receipts from live state

_persistLocalState prunes into a separate observed map, leaving _effectiveState unchanged. As new attention IDs arrive, expired seen:msg: entries therefore remain in memory and participate in subsequent save scans. Please prune these obsolete row receipts from live state too. If adding capacity eviction, dropping a row hint should not advance the read floor—it quiets the row but does not mark anything read.

Posted by Codex (gpt-6.1-sol) on behalf of kylez

}
}
if (ordinary) marks[seenContextKey(channelId)] = newest;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Optional: the saved cutoff depends on frame delivery and never retreats.

Marks are written incrementally while the page is in front, and seen:<channel> only advances when the pass finds unseen ordinary backlog. Two consequences:

  • If ordinary t=100 and a mention t=120 land in one pass, mobile saves 120 (same as desktop). If they land in separate passes, it saves 100, so a late ordinary t=110 relights the row. That's conservative, and the synced value keeps clients consistent, but it isn't deterministic.
  • If a thread reply at t=120 is deleted during the visit after the cut reached 120, the cut stays at 120. Desktop builds its exit snapshot from retained evidence and would cut at the newest remaining event, so a late ordinary message stamped between them stays hidden on mobile but not on desktop.

Desktop freezes the snapshot at visit end (unread.ts seeChannel). Saving the cut once from retained evidence on cover, background or exit would fix both and make it match desktop. The deletion case needs a deletion during the visit plus a delayed message inside that window, so I wouldn't block on it.

return marks;
}

typedef _MemoEntry = ({
int revision,
int? latestObserved,
Expand Down
23 changes: 9 additions & 14 deletions mobile/lib/features/channels/channels_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,15 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
}
}

void _notifyUnreadReadinessChanged() {
final previous = _unreadReadinessChanged;
_unreadReadinessChanged = Completer<void>();
previous.complete();
}
/// Unread evidence changes for [channelId], without scanning the registry.
int observedUnreadRevisionFor(String channelId) =>
_observedUnreadRevisions.of(channelId);

/// [channelId]'s observed evidence for the active visit.
Map<String, ObservedUnreadEvent> observedUnreadEventsFor(String channelId) =>
UnmodifiableMapView(
_observedUnreadEventsByChannel[channelId] ?? const {},
);

Map<String, Map<String, ObservedUnreadEvent>>
get observedUnreadEventsByChannel => ObservedUnreadSnapshot({
Expand Down Expand Up @@ -970,15 +974,6 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
}
}

/// Adds [event]'s thread to the in-memory interest sets; true when new.
/// Callers persist with [_writeThreadInterestStores], once per batch: each
/// write re-encodes both whole sets on the main thread.
bool _addSelfThreadInterest(NostrEvent event) {
final ref = event.threadReference;
final target = ref.rootId != null ? _participatedRootIds : _authoredRootIds;
return target.add(ref.rootId ?? event.id);
}

void _writeThreadInterestStores(String pubkey) {
final normalizedPubkey = pubkey.toLowerCase();
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,19 @@ int? observedUnreadEventReadAt(
if (event.channelCatchUp) markerOf(activityContextKey(channelId)),
]);
}

/// Whether [channelId]'s row has seen [event] (see [seenContextKey]): an
/// attention message by its own receipt, whatever its timestamp, and an
/// ordinary message by the channel's row hint. [contexts] is the stored
/// map, so the retention floor cannot stand in for a missing receipt.
bool rowSawObservedUnreadEvent(
ObservedUnreadEvent event,
String channelId,
Map<String, int> contexts,
) {
if (!event.channelCatchUp) {
return contexts.containsKey(seenMessageContextKey(event.id));
}
final seenAt = contexts[seenContextKey(channelId)];
return seenAt != null && event.createdAt <= seenAt;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../../../shared/me/me_sync.dart';
import '../channels_provider.dart';
import '../../../shared/read_state/read_state_provider.dart';
import 'observed_unread_event.dart';
Expand All @@ -17,6 +18,11 @@ class UnreadBadgeState {
final unreadBadgeProvider = Provider<UnreadBadgeState>((ref) {
final channelsAsync = ref.watch(channelsProvider);
final readState = ref.watch(readStateProvider);
final legacySoloIds = ref.watch(
meGroupsProvider.select(
(groups) => groups.value?.channels ?? const <String>[],
),
);

return channelsAsync.when(
data: (channels) {
Expand All @@ -38,12 +44,24 @@ final unreadBadgeProvider = Provider<UnreadBadgeState>((ref) {
if (!latestObservedByChannel.containsKey(channel.id)) continue;

final observedEvents = observedEventsByChannel[channel.id];
int? readAtForObservedEvent(ObservedUnreadEvent event) =>
observedUnreadEventReadAt(
event,
channel.id,
readState.effectiveTimestamp,
);
// Match Home and Me, which display raw unread for Solo chats.
final applyRowMarks =
!channel.isDm && !channel.isSoloChat(legacySoloIds);
int? readAtForObservedEvent(ObservedUnreadEvent event) {
if (applyRowMarks &&
rowSawObservedUnreadEvent(
event,
channel.id,
readState.contexts,
)) {
return event.createdAt;
}
return observedUnreadEventReadAt(
event,
channel.id,
readState.effectiveTimestamp,
);
}

final unreadCount = countUnreadObservedEvents(
observedEvents,
Expand All @@ -67,21 +85,7 @@ final unreadBadgeProvider = Provider<UnreadBadgeState>((ref) {
observedEvents,
readAtForObservedEvent,
);
if (badgeCount > 0) {
general += badgeCount;
} else {
// Only ordinary backlog is left. Count it when its row is bold:
// a synced `seen:<channel>` mark quiets backlog at or before it.
final seenAt = readState.contexts['seen:${channel.id}'];
final rowShowsBacklog =
seenAt == null ||
observedEvents!.values.any((event) {
if (event.createdAt <= seenAt) return false;
final readAt = readAtForObservedEvent(event);
return readAt == null || event.createdAt > readAt;
});
if (rowShowsBacklog) general++;
}
general += badgeCount > 0 ? badgeCount : 1;
}
}

Expand Down
19 changes: 19 additions & 0 deletions mobile/lib/shared/read_state/read_state_format.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,25 @@ String threadContextKey(String rootId) => '$threadContextPrefix$rootId';
String activityContextKey(String channelId) => 'activity:$channelId';
String threadActivityContextKey(String rootId) => 'thread-activity:$rootId';

/// Row hints, written by this app and `buzz-app` when the reader opens a
/// channel (`buzz-app`'s `docs/unread.md`). They quiet the channel's row in
/// the channel list and app badge. `seen:<channel>` is the visit's timestamp
/// cutoff for ordinary activity and syncs to the user's other devices.
String seenContextKey(String channelId) => 'seen:$channelId';
const _seenMessagePrefix = 'seen:msg:';

/// Local receipt for attention observed during a channel visit.
String seenMessageContextKey(String messageId) =>
'$_seenMessagePrefix$messageId';

/// Whether [contextId] is a device-local row receipt.
bool isSeenMessageContext(String contextId) =>
contextId.startsWith(_seenMessagePrefix);

/// Whether a read-position slot can carry this context.
bool isReadStateSlotContext(String contextId) =>
!isOverrideContext(contextId) && !isSeenMessageContext(contextId);

/// Whether `activity:<channel>` reads a message: an ordinary top-level
/// message, not a reply, mention, broadcast or DM. Callers pass a message
/// with the broadcast tag as [isReply], with or without a parent:
Expand Down
27 changes: 26 additions & 1 deletion mobile/lib/shared/read_state/read_state_journal.dart
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,39 @@ extension ReadStateJournal on ReadStateManager {
stored.contexts.entries.where(
(entry) =>
stored.publishableContextIds.contains(entry.key) &&
!isOverrideContext(entry.key) &&
isReadStateSlotContext(entry.key) &&
!entry.key.startsWith(msgContextPrefix),
),
);
}
_persistLocalState();
}

/// Save the visit's hints in one batch. The channel cutoff rides the next
/// read-state publish or flush without scheduling its own snapshot.
void markChannelRowSeen(Map<String, int> marks) {
final floor = readStateFloor(_now());
var changed = false;
for (final MapEntry(:key, :value) in marks.entries) {
if (value <= floor) continue;
if (_advanceContext(
key,
value,
publishable: !isSeenMessageContext(key),
)) {
changed = true;
}
}
if (!changed) return;
// Expired receipts have already fallen behind the read floor. Retire
// them in memory as well as on disk.
_effectiveState.removeWhere(
(key, value) => isSeenMessageContext(key) && value <= floor,
);
_persistLocalState();
_onChanged();
}

/// The journal field that keeps a retained packet for coordinate [key].
String _pendingField(String key) => key.startsWith(threadFollowsDTagPrefix)
? 'followPending'
Expand Down
2 changes: 1 addition & 1 deletion mobile/lib/shared/read_state/read_state_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ class ReadStateManager {
}
}
for (final entry in decoded.blob.contexts.entries) {
if (isOverrideContext(entry.key)) continue;
if (!isReadStateSlotContext(entry.key)) continue;
if (_applyRemoteContextTimestamp(
contextId: entry.key,
timestamp: entry.value,
Expand Down
5 changes: 5 additions & 0 deletions mobile/lib/shared/read_state/read_state_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,11 @@ class ReadStateNotifier extends Notifier<ReadStateState> {
if (explicit) clearCovered(scope: contextId);
}

/// Saves channel row hints without advancing any read frontier.
void markChannelRowSeen(Map<String, int> marks) {
_currentManager?.markChannelRowSeen(marks);
}

/// Ends the device-local marks a read covers, whether or not a frontier
/// moved (NIP-RS Clearing): [displayed] messages, and for a catch-up or
/// explicit read [scope], a channel's top-level messages or a
Expand Down
Loading
Loading