Skip to content

Commit 81a07a9

Browse files
committed
fix(notifications): address code review findings for two-tier badge
Badge E2E test assumed a clean slate but watercooler mock channel has seeded forum history that survives as unread — record baseline badge state before injecting the test message and assert return-to-baseline rather than hardcoded "none". Mobile backfill used limit:50 without since, missing high-priority events beyond page 50. Now uses the read marker as since and limit:200. Batches backfill requests (5 concurrent) to avoid relay saturation. _contextSourceCreatedAt was not persisted to SharedPreferences, losing last-writer-wins protection on app restart. Now persisted alongside forcedContextIds. reinitializeRemote could race with an in-flight _publish at await suspension points. Now awaits the publish Completer before proceeding. Stabilize highPriorityUnreadChannelIds Set identity with content-based comparison to avoid spurious downstream memo re-runs. Validate PNG filenames in post-screenshots.sh before git mktree.
1 parent 9282bda commit 81a07a9

7 files changed

Lines changed: 113 additions & 8 deletions

File tree

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ const overrides = new Map([
3939
["src/features/channels/ui/ChannelManagementSheet.tsx", 800],
4040
["src/features/channels/ui/ChannelPane.tsx", 540], // composer/timeline/sidebar orchestration + anchored agent activity footers + imetaMedia threading on editTarget + thread follow props passthrough
4141
["src/features/channels/ui/ChannelScreen.tsx", 580], // profile panel state + mutual exclusion wiring + ProfilePanelProvider context + agent typing classification + imetaMedia projection on editTarget + thread follow wiring from AppShell context
42-
["src/features/channels/useUnreadChannels.ts", 835], // NIP-RS read marker tracking + participated/authored/followed thread ID sets + localStorage persistence + catch-up REQ with thread activity collection + thread reply activity feed items + mutedRootIds denylist with localStorage persistence + muteThread/unmuteThread callbacks + markChannelRead latestByChannelRef fallback chain (matches markChannelUnread) + two-tier badge: latestHighPriorityByChannelRef + highPriorityUnreadChannelIds memo tracking DMs + @mentions + broadcast replies + markChannelRead observed-latest ref clearing
42+
["src/features/channels/useUnreadChannels.ts", 865], // NIP-RS read marker tracking + participated/authored/followed thread ID sets + localStorage persistence + catch-up REQ with thread activity collection + thread reply activity feed items + mutedRootIds denylist with localStorage persistence + muteThread/unmuteThread callbacks + markChannelRead latestByChannelRef fallback chain (matches markChannelUnread) + two-tier badge: latestHighPriorityByChannelRef + highPriorityUnreadChannelIds memo tracking DMs + @mentions + broadcast replies + markChannelRead observed-latest ref clearing + Set identity stabilization for downstream memo perf
4343
["src/features/notifications/hooks.ts", 535], // notification settings + feed notification lifecycle + profile batch resolution + truncated-pubkey guard + badge state
4444
["src/features/home/ui/HomeView.tsx", 505], // inbox/feed orchestration + thread context + reply/delete flow + NIP-RS read-state projection wiring (useHomeInboxReadState)
4545
["src/features/messages/hooks.ts", 525], // message query/mutation hooks + optimistic updates + custom-emoji reaction URL resolution (reactionEmojiUrl from cached relay set) + outgoing tag split (splitOutgoingTags) routing custom-emoji tags through the dedicated emoji_tags send arg so they skip the imeta-only gate

‎desktop/src/features/channels/useUnreadChannels.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,14 @@ function toUnixSeconds(isoOrMs: string | null | undefined): number | null {
212212
return ms === null ? null : Math.floor(ms / 1_000);
213213
}
214214

215+
function setsEqual(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {
216+
if (a.size !== b.size) return false;
217+
for (const item of a) {
218+
if (!b.has(item)) return false;
219+
}
220+
return true;
221+
}
222+
215223
export function useUnreadChannels(
216224
channels: Channel[],
217225
activeChannel: Channel | null,
@@ -729,7 +737,7 @@ export function useUnreadChannels(
729737
// than the read marker. Forced-unread channels are dot tier only (not
730738
// high-priority). Both sets share identical deps and always invalidate
731739
// together, so they are computed in a single memo.
732-
const { unreadChannelIds, highPriorityUnreadChannelIds } =
740+
const rawUnread =
733741
// biome-ignore lint/correctness/useExhaustiveDependencies: readStateVersion and latestVersion are intentional invalidation signals
734742
React.useMemo(() => {
735743
if (!isReadStateReady) {
@@ -789,6 +797,27 @@ export function useUnreadChannels(
789797
readStateVersion,
790798
]);
791799

800+
// Stabilize Set references: only replace when contents actually change,
801+
// so downstream memos don't re-run on every render when sets are equal.
802+
const prevUnreadRef = React.useRef<ReadonlySet<string>>(new Set());
803+
const prevHighPriorityRef = React.useRef<ReadonlySet<string>>(new Set());
804+
805+
const unreadChannelIds = setsEqual(
806+
rawUnread.unreadChannelIds,
807+
prevUnreadRef.current,
808+
)
809+
? prevUnreadRef.current
810+
: rawUnread.unreadChannelIds;
811+
prevUnreadRef.current = unreadChannelIds;
812+
813+
const highPriorityUnreadChannelIds = setsEqual(
814+
rawUnread.highPriorityUnreadChannelIds,
815+
prevHighPriorityRef.current,
816+
)
817+
? prevHighPriorityRef.current
818+
: rawUnread.highPriorityUnreadChannelIds;
819+
prevHighPriorityRef.current = highPriorityUnreadChannelIds;
820+
792821
const unreadChannelIdsRef = React.useRef(unreadChannelIds);
793822
unreadChannelIdsRef.current = unreadChannelIds;
794823

‎desktop/tests/e2e/badge.spec.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,11 @@ test("mark-as-read via context menu clears channel unread indicator", async ({
166166
await expect(page.getByTestId("chat-title")).toHaveText("general");
167167
await waitForMockLiveSubscription(page, "random");
168168

169+
// Wait for catch-up to settle, then record baseline badge state
170+
// (other mock channels may have pre-existing unreads from seeded history)
171+
await page.waitForTimeout(2000);
172+
const baselineBadge = await getBadgeState(page);
173+
169174
await page.evaluate(
170175
({ pubkey }) => {
171176
window.__SPROUT_E2E_EMIT_MOCK_MESSAGE__?.({
@@ -184,7 +189,7 @@ test("mark-as-read via context menu clears channel unread indicator", async ({
184189
await page.getByText("Mark as read").click();
185190

186191
await expect(page.getByTestId("channel-unread-random")).toHaveCount(0);
187-
await waitForBadgeState(page, { state: "none" });
192+
await waitForBadgeState(page, { state: baselineBadge.state });
188193
});
189194

190195
test("mark-as-unread via context menu shows dot badge", async ({ page }) => {

‎mobile/lib/features/channels/channels_provider.dart‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import 'dart:async';
2+
import 'dart:math';
23

34
import 'package:flutter/widgets.dart';
45
import 'package:hooks_riverpod/hooks_riverpod.dart';
@@ -7,6 +8,7 @@ import '../../shared/relay/relay.dart';
78
import '../../shared/utils/string_utils.dart';
89
import 'channel.dart';
910
import 'channel_management_provider.dart' show channelDetailsProvider;
11+
import 'read_state/read_state_provider.dart';
1012
import 'unread_badge/is_high_priority_event.dart';
1113

1214
const _channelTypeOrder = {'stream': 0, 'forum': 1, 'dm': 2};
@@ -351,6 +353,7 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
351353
if (myPk == null) return;
352354

353355
final session = ref.read(relaySessionProvider.notifier);
356+
final readState = ref.read(readStateProvider);
354357
final futures = <Future<void>>[];
355358

356359
for (final channel in channels) {
@@ -366,10 +369,17 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
366369
continue;
367370
}
368371

369-
futures.add(_backfillHighPriorityForChannel(session, channel, myPk));
372+
final readAt = readState.effectiveTimestamp(channel.id);
373+
futures.add(
374+
_backfillHighPriorityForChannel(session, channel, myPk, readAt),
375+
);
370376
}
371377

372-
await Future.wait(futures);
378+
// Batch into groups of 5 to avoid saturating the relay.
379+
const batchSize = 5;
380+
for (var i = 0; i < futures.length; i += batchSize) {
381+
await Future.wait(futures.sublist(i, min(i + batchSize, futures.length)));
382+
}
373383

374384
// Trigger unreadBadgeProvider to re-evaluate now that the map is populated.
375385
state = state.whenData((channels) => List<Channel>.of(channels));
@@ -379,16 +389,20 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
379389
RelaySessionNotifier session,
380390
Channel channel,
381391
String myPk,
392+
int? readAt,
382393
) async {
383-
// For non-DM channels, fetch recent events and scan for high-priority ones.
394+
// For non-DM channels, fetch events since the last read timestamp and scan
395+
// for high-priority ones. Using `since` avoids fetching messages the user
396+
// has already seen, and `limit: 200` covers deep mention backfills.
384397
try {
385398
final events = await session.fetchHistory(
386399
NostrFilter(
387400
kinds: EventKind.channelEventKinds,
388401
tags: {
389402
'#h': [channel.id],
390403
},
391-
limit: 50,
404+
since: readAt ?? 0,
405+
limit: 200,
392406
),
393407
);
394408

‎mobile/lib/features/channels/read_state/read_state_manager.dart‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ class ReadStateManager {
5959
bool _initialized = false;
6060
bool _disposed = false;
6161
bool _isPublishing = false;
62+
Completer<void>? _publishCompleter;
6263
bool _remoteUnsupported = false;
6364
int _maxFetchedCreatedAt = 0;
6465
final Set<String> _forcedContextIds = {};
@@ -138,6 +139,9 @@ class ReadStateManager {
138139

139140
Future<void> reinitializeRemote() async {
140141
if (_disposed || !_remoteEnabled) return;
142+
if (_isPublishing) {
143+
await _publishCompleter?.future;
144+
}
141145
_unsubscribeLive?.call();
142146
_unsubscribeLive = null;
143147
await _fetchAndMerge();
@@ -362,6 +366,8 @@ class ReadStateManager {
362366
}
363367
if (_isPublishing) return;
364368

369+
final completer = Completer<void>();
370+
_publishCompleter = completer;
365371
_isPublishing = true;
366372
try {
367373
await _fetchOwnBlobBeforePublish();
@@ -406,6 +412,10 @@ class ReadStateManager {
406412
debugPrint('[ReadStateManager] publish failed: $error');
407413
} finally {
408414
_isPublishing = false;
415+
completer.complete();
416+
if (_publishCompleter == completer) {
417+
_publishCompleter = null;
418+
}
409419
}
410420
}
411421

@@ -466,6 +476,9 @@ class ReadStateManager {
466476
_forcedContextIds
467477
..clear()
468478
..addAll(stored.forcedContextIds);
479+
_contextSourceCreatedAt
480+
..clear()
481+
..addAll(stored.sourceCreatedAt);
469482
_persistLocalState();
470483
}
471484

@@ -475,6 +488,7 @@ class ReadStateManager {
475488
_effectiveState,
476489
_publishableContextIds,
477490
_forcedContextIds,
491+
_contextSourceCreatedAt,
478492
);
479493
}
480494

‎mobile/lib/features/channels/read_state/read_state_storage.dart‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ String localPublishableContextKey(String pubkey) =>
2020
String localForcedContextKey(String pubkey) =>
2121
'sprout.channel-read-state.forced.v1:$pubkey';
2222

23+
String localSourceCreatedAtKey(String pubkey) =>
24+
'sprout.channel-read-state.source-created-at.v1:$pubkey';
25+
2326
String clientIdKey(String pubkey) => '$_clientIdKeyPrefix:$pubkey';
2427

2528
String slotIdKey(String pubkey) => '$_slotIdKeyPrefix:$pubkey';
@@ -28,14 +31,17 @@ class StoredReadState {
2831
final Map<String, int> contexts;
2932
final Set<String> publishableContextIds;
3033
final Set<String> forcedContextIds;
34+
final Map<String, int> sourceCreatedAt;
3135

3236
StoredReadState({
3337
required Map<String, int> contexts,
3438
required Set<String> publishableContextIds,
3539
required Set<String> forcedContextIds,
40+
required Map<String, int> sourceCreatedAt,
3641
}) : contexts = Map.unmodifiable(contexts),
3742
publishableContextIds = Set.unmodifiable(publishableContextIds),
38-
forcedContextIds = Set.unmodifiable(forcedContextIds);
43+
forcedContextIds = Set.unmodifiable(forcedContextIds),
44+
sourceCreatedAt = Map.unmodifiable(sourceCreatedAt);
3945
}
4046

4147
class ReadStateStorage {
@@ -76,6 +82,7 @@ class ReadStateStorage {
7682
contexts: _readContexts(pubkey),
7783
publishableContextIds: _readPublishableContextIds(pubkey),
7884
forcedContextIds: _readForcedContextIds(pubkey),
85+
sourceCreatedAt: _readSourceCreatedAt(pubkey),
7986
);
8087
}
8188

@@ -84,6 +91,7 @@ class ReadStateStorage {
8491
Map<String, int> contexts,
8592
Set<String> publishableContextIds,
8693
Set<String> forcedContextIds,
94+
Map<String, int> sourceCreatedAt,
8795
) {
8896
final state = <String, String>{};
8997
for (final entry in contexts.entries) {
@@ -99,6 +107,10 @@ class ReadStateStorage {
99107
localForcedContextKey(pubkey),
100108
jsonEncode(forcedContextIds.toList()),
101109
);
110+
_prefs.setString(
111+
localSourceCreatedAtKey(pubkey),
112+
jsonEncode(sourceCreatedAt.map((k, v) => MapEntry(k, v.toString()))),
113+
);
102114
}
103115

104116
Map<String, int> _readContexts(String pubkey) {
@@ -177,6 +189,33 @@ class ReadStateStorage {
177189
if (value is String) value,
178190
};
179191
}
192+
193+
Map<String, int> _readSourceCreatedAt(String pubkey) {
194+
final raw = _prefs.getString(localSourceCreatedAtKey(pubkey));
195+
if (raw == null || raw.isEmpty) return {};
196+
197+
final Object? parsed;
198+
try {
199+
parsed = jsonDecode(raw);
200+
} catch (_) {
201+
return {};
202+
}
203+
204+
final record = asStringObjectMap(parsed);
205+
if (record == null) return {};
206+
207+
final result = <String, int>{};
208+
for (final entry in record.entries) {
209+
final value = entry.value;
210+
if (value is int) {
211+
result[entry.key] = value;
212+
} else if (value is String) {
213+
final parsed = int.tryParse(value);
214+
if (parsed != null) result[entry.key] = parsed;
215+
}
216+
}
217+
return result;
218+
}
180219
}
181220

182221
String generateReadStateSlotId() {

‎scripts/post-screenshots.sh‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ NEW_ENTRIES=""
3535
IMAGE_URLS=()
3636
for PNG in "${PNGS[@]}"; do
3737
FILENAME=$(basename "$PNG")
38+
if ! [[ "$FILENAME" =~ ^[a-zA-Z0-9_.-]+$ ]]; then
39+
echo "error: invalid PNG filename (must be alphanumeric, dots, hyphens, underscores): $FILENAME" >&2
40+
exit 1
41+
fi
3842
BLOB=$(git hash-object -w "$PNG")
3943
TREE_PATH="pr-${PR}--${FILENAME}"
4044
NEW_ENTRIES+="$(printf '100644 blob %s\t%s' "$BLOB" "$TREE_PATH")"$'\n'

0 commit comments

Comments
 (0)