Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
4c0c867
Cache recently opened mobile thread replies
wesbillman Nov 20, 2026
71c5e2b
Land on saved thread replies after an offline query failure
wesbillman Nov 20, 2026
49a071c
Announce confirmed thread access loss to screen readers
wesbillman Nov 20, 2026
2297d93
Fence thread cache writes and refresh pruned previews
wesbillman Nov 21, 2026
940fd8f
Drain the cache queue before checking preview retirement
wesbillman Nov 21, 2026
9756f89
Merge remote-tracking branch 'origin/main' into mobile-saved-thread-p…
wesbillman Nov 21, 2026
91e476d
Fix offline thread entry and stale saved edits
wesbillman Nov 23, 2026
8bc759e
Merge remote-tracking branch 'origin/main' into mobile-saved-thread-p…
wesbillman Nov 23, 2026
1168adb
Bound writer verification for saved thread pages
wesbillman Nov 23, 2026
1ea2170
Keep saved thread previews stable and scope edit checks
wesbillman Nov 23, 2026
2e0ebb2
Use saved thread evidence to detect stale replica reads
wesbillman Nov 23, 2026
e6138e6
Merge remote-tracking branch 'origin/main' into mobile-saved-thread-p…
wesbillman Nov 23, 2026
79d7b44
Brace the saved-thread test polling condition
wesbillman Nov 23, 2026
fe5b19b
Retain saved thread pages when mutation verification fails
wesbillman Nov 23, 2026
24e4f63
Keep saved thread links and retry controls usable
wesbillman Nov 23, 2026
30bf267
Record exact pruned thread IDs for cache verification
wesbillman Nov 23, 2026
dca8250
Keep unrelated cache pages during a full-disk prune
wesbillman Nov 23, 2026
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
2 changes: 2 additions & 0 deletions mobile/lib/features/channels/channel_detail_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ import '../../shared/read_state/deferred_read_state_update.dart';
import '../../shared/read_state/read_state_provider.dart';
import '../../shared/read_state/read_state_time.dart';
import 'reaction_row.dart';
import 'saved_channel_page.dart';
import '../../shared/emoji/recent_emoji_provider.dart';
import 'send_message_provider.dart';
import '../profile/user_profile_sheet.dart';
Expand All @@ -131,6 +132,7 @@ import 'reading_marks.dart';
import 'timeline_message.dart';

part 'channel_detail_page/message_list.dart';
part 'channel_detail_page/initial_thread_route.dart';
part 'channel_detail_page/jump_to_oldest_unread_button.dart';
part 'channel_detail_page/row_cache.dart';
part 'channel_detail_page/placement_route.dart';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
part of '../channel_detail_page.dart';

extension on _MessageList {
void _useInitialThreadRoute(BuildContext context, WidgetRef ref) {
final opened = useRef(false);
final rootId = initialThreadRootId;
final channelHead = rootId == null
? null
: allMessages.where((message) => message.id == rootId).firstOrNull;
final preview = rootId == null || channelHead != null || opened.value
? null
: ref.watch(
savedThreadPreviewProvider((channelId: channelId, rootId: rootId)),
);
final saved = preview?.isLoading == false ? preview?.value : null;
final live = saved == null
? null
: ref.watch(channelMessagesProvider(channelId)).value;
final head = useMemoized(() {
if (channelHead != null || saved == null) return channelHead;
return formatTimeline(
mergeThreadEvents(saved, live ?? const []),
currentPubkey: currentPubkey,
).where((message) => message.id == rootId).firstOrNull;
}, [channelHead, saved, live, currentPubkey, rootId]);
useEffect(() {
if (opened.value || head == null) return null;
var cancelled = false;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (cancelled ||
!context.mounted ||
ModalRoute.of(context)?.isCurrent != true) {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

🤖 Recommended blocker: a deferred deep link can open its thread long after entry. The old effect consumed the intent before its post-frame check. Here opened is set only after isCurrent passes, and the effect re-runs on every allMessages change.

Failure: a notification opens the channel. The head takes a moment to resolve (history load, or the 250 ms delay plus the disk read for a saved head), and meanwhile the user opens channel details, so this callback bails. They come back and read the channel. The next incoming message rebuilds allMessages, and the thread pushes over them. With replaceCurrentRoute, it replaces the channel page.

Fix: either consume the intent when the head resolves while the route is covered, as before, or keep it pending only until the route next becomes current. Don't re-arm it on later allMessages changes.

return;
}
final error = ref.read(channelMessagesProvider(channelId)).error;
if (error != null && isRelayChannelAccessDenied(error)) return;
if (channelHead == null && rootId != null) {
final current = ref.read(
savedThreadPreviewProvider((channelId: channelId, rootId: rootId)),
);
if (current.isLoading || !identical(current.value, saved)) return;
}
opened.value = true;
final route = MaterialPageRoute<void>(
builder: (_) => ThreadDetailPage(
threadHead: head,
headFromSavedPage: channelHead == null,
allMessages: allMessages,
channelId: channelId,
currentPubkey: currentPubkey,
isMember: isMember,
isArchived: isArchived,
initialMessageId: initialMessageId,
),
);
final navigator = Navigator.of(context);
switch (initialThreadRouteBehavior) {
case InitialThreadRouteBehavior.push:
navigator.push(route);
case InitialThreadRouteBehavior.replaceCurrentRoute:
navigator.pushReplacement(route);
}
});
return () => cancelled = true;
}, [head, channelHead, allMessages, initialThreadRouteBehavior]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ class _MessageList extends HookConsumerWidget {
final latestEntryId = entries.isEmpty ? null : entries.last.message.id;
final previousLatestEntryId = useRef<String?>(null);
final observedLocalSendIds = useRef(localSendAnimations.keys.toSet());
final didOpenInitialThread = useRef(false);
final didJumpToInitialMessage = useRef(false);
final isUnreadNavigationDismissed = useState(false);
final detachedWhileUnreadShown = useRef(false);
Expand Down Expand Up @@ -729,40 +728,7 @@ class _MessageList extends HookConsumerWidget {
};
}, [appView, itemScrollController]);

useEffect(() {
if (initialThreadRootId == null || didOpenInitialThread.value) {
return null;
}
final threadHead = allMessages
.where((message) => message.id == initialThreadRootId)
.firstOrNull;
if (threadHead == null) return null;
didOpenInitialThread.value = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!context.mounted || ModalRoute.of(context)?.isCurrent != true) {
return;
}
final route = MaterialPageRoute<void>(
builder: (_) => ThreadDetailPage(
threadHead: threadHead,
allMessages: allMessages,
channelId: channelId,
currentPubkey: currentPubkey,
isMember: isMember,
isArchived: isArchived,
initialMessageId: initialMessageId,
),
);
final navigator = Navigator.of(context);
switch (initialThreadRouteBehavior) {
case InitialThreadRouteBehavior.push:
navigator.push(route);
case InitialThreadRouteBehavior.replaceCurrentRoute:
navigator.pushReplacement(route);
}
});
return null;
}, [initialThreadRootId, allMessages, initialThreadRouteBehavior]);
_useInitialThreadRoute(context, ref);

useEffect(() {
final targetIndex = reversedIndexOf(initialMessageId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ class ChannelActions {
final recorded = _ref
.read(savedMessageStoreProvider)
.removeChannel(scope, channelId, deferDisk: true);
_ref.invalidate(savedChannelPreviewProvider(channelId));
invalidateSavedMessagePreviews(_ref, channelId);
await recorded;
}
_ensureCommunityValid();
Expand Down
28 changes: 21 additions & 7 deletions mobile/lib/features/channels/channel_messages_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -273,12 +273,10 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
(event.kind == EventKind.deletion ||
event.kind == EventKind.nip29DeleteEvent ||
event.kind == EventKind.streamMessageEdit)) {
// Remove stale rows and retire a pending save of the old page.
final targets = {
pruneSavedMessageTargets(ref, cacheScope, channelId, {
for (final tag in event.tags)
if (tag.length > 1 && tag[0] == 'e') tag[1],
};
cache.removeChannelEvents(cacheScope, channelId, targets);
}, edited: event.kind == EventKind.streamMessageEdit);
}
_handleLiveEvent(event);
},
Expand Down Expand Up @@ -320,6 +318,10 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
initVersion,
);
if (!_isCurrentInit(initVersion)) return;
// Legacy history can return an empty result for a refused read.
if (_accessDenial != null && !_usingChannelWindow && history.isEmpty) {
return;
}
if (!_usingChannelWindow) {
_legacyHistoryCursor = history.isEmpty
? null
Expand All @@ -345,7 +347,7 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
state = AsyncData(merged);
if (ticket != null && _hasListeners) {
unawaited(
saveChannelPage(
saveMessagePage(
ref,
cache,
ticket,
Expand Down Expand Up @@ -386,6 +388,15 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
}
}

bool get isAccessDenied => _accessDenial != null;

void denyAccessFromThread(Object error, StackTrace stackTrace) => _denyAccess(
error,
stackTrace,
ref.read(savedMessageStoreProvider),
ref.read(savedMessageScopeProvider),
);

void _denyAccess(
Object error,
StackTrace stackTrace,
Expand All @@ -406,7 +417,7 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
_noticeAux.clear();
if (scope != null) {
unawaited(cache.removeChannel(scope, channelId));
ref.invalidate(savedChannelPreviewProvider(channelId));
invalidateSavedMessagePreviews(ref, channelId);
}
final denial = AsyncError<List<NostrEvent>>(error, stackTrace);
_accessDenial = denial;
Expand Down Expand Up @@ -788,6 +799,7 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
Set<String> scopedTargetIds = const {},
Set<String> reconciledTargetIds = const {},
}) {
if (_accessDenial != null) return;
var events = state.value ?? _lastKnownMessages ?? const <NostrEvent>[];
for (final event in deletions) {
final targets = event.tags
Expand Down Expand Up @@ -881,7 +893,8 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
Set<String> provisionalReplyIds = const {},
int? queryVersion,
}) {
if (queryVersion != null && _threadQueryVersions[rootId] != queryVersion) {
if (_accessDenial != null ||
queryVersion != null && _threadQueryVersions[rootId] != queryVersion) {
return false;
}
final evidenceVersion = queryVersion ?? ++_threadQuerySerial;
Expand Down Expand Up @@ -948,6 +961,7 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
/// Caches confirmed thread replies before their optimistic overlay is cleared.
/// Thread queries must not invalidate themselves as live relay events do.
void cacheConfirmedThreadReplies(Iterable<NostrEvent> replies) {
if (_accessDenial != null) return;
_replyOwnership.record(replies);
var events = state.value ?? _lastKnownMessages ?? const <NostrEvent>[];
for (final reply in _boundedReplies(replies)) {
Expand Down
18 changes: 13 additions & 5 deletions mobile/lib/features/channels/channel_unread_deletions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,23 @@ extension _UnreadDeletions on ChannelsNotifier {
_removeSavedMessageTargets(channelId, {
for (final tag in event.tags)
if (tag.length >= 2 && tag[0] == 'e') tag[1],
});
}, edited: true);
}

void _removeSavedMessageTargets(String channelId, Set<String> targets) {
void _removeSavedMessageTargets(
String channelId,
Set<String> targets, {
bool edited = false,
}) {
if (targets.isEmpty) return;
final scope = _lifecycleRef.read(savedMessageScopeProvider);
if (scope == null) return;
_lifecycleRef
.read(savedMessageStoreProvider)
.removeChannelEvents(scope, channelId, targets);
pruneSavedMessageTargets(
_lifecycleRef,
scope,
channelId,
targets,
edited: edited,
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ extension ChannelsNotifierJoins on ChannelsNotifier {
cache.removeChannel(scope, channelId),
];
for (final channelId in removed) {
_lifecycleRef.invalidate(savedChannelPreviewProvider(channelId));
invalidateSavedMessagePreviews(_lifecycleRef, channelId);
}
// Keep the old membership on disk until its cache purge runs.
await _fenced(fence, Future.wait(purges));
Expand Down
98 changes: 73 additions & 25 deletions mobile/lib/features/channels/saved_channel_page.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:isolate';

import 'package:flutter/scheduler.dart';
Expand All @@ -17,30 +18,71 @@ typedef SavedChannelPreview = ({
/// A disk page goes straight to the view. The live notifier can replace the
/// preview without ever folding its old rows into current relay history.
final savedChannelPreviewProvider = FutureProvider.autoDispose
.family<SavedChannelPreview?, String>((ref, channelId) async {
final scope = ref.watch(savedMessageScopeProvider);
if (scope == null) return null;
final cache = ref.watch(savedMessageStoreProvider);
var disposed = false;
ref.onDispose(() => disposed = true);
if (ref.read(relaySessionProvider).status == SessionStatus.connected) {
await Future<void>.delayed(const Duration(milliseconds: 250));
}
// A covered route can pause its listeners while the read finishes.
// Retry retired tickets until this provider is disposed.
while (!disposed) {
final ticket = cache.capture(scope, (channelId: channelId, rootId: ''));
final events = await cache.read(ticket);
if (disposed) return null;
if (!cache.isCurrent(ticket)) continue;
if (events == null) return null;
final preview = await _preparePreview(events);
if (disposed) return null;
if (cache.isCurrent(ticket)) return preview;
}
return null;
.family<SavedChannelPreview?, String>(
(ref, channelId) => _readSavedPage(ref, (
channelId: channelId,
rootId: '',
), _preparePreview),
);

final _threadPreviewRevision = Provider.autoDispose.family<Object, String>(
(ref, channelId) => Object(),
);

final savedThreadPreviewProvider = FutureProvider.autoDispose
.family<List<NostrEvent>?, SavedMessagePage>((ref, page) {
ref.watch(_threadPreviewRevision(page.channelId));
return _readSavedPage(ref, page, (events) => events);
});

void invalidateSavedMessagePreviews(Ref ref, String channelId) {
ref.invalidate(savedChannelPreviewProvider(channelId));
ref.invalidate(_threadPreviewRevision(channelId));
}

/// Retires the displayed thread pages as well as their old disk rows.
void pruneSavedMessageTargets(
Ref ref,
SavedMessageScope scope,
String channelId,
Set<String> targets, {
bool edited = false,
}) {
if (targets.isEmpty) return;
ref
.read(savedMessageStoreProvider)
.removeChannelEvents(scope, channelId, targets, edited: edited);
ref.invalidate(_threadPreviewRevision(channelId));
}

Future<T?> _readSavedPage<T>(
Ref ref,
SavedMessagePage page,
FutureOr<T> Function(List<NostrEvent>) prepare,
) async {
final scope = ref.watch(savedMessageScopeProvider);
if (scope == null) return null;
final cache = ref.watch(savedMessageStoreProvider);
var disposed = false;
ref.onDispose(() => disposed = true);
if (ref.read(relaySessionProvider).status == SessionStatus.connected) {
await Future<void>.delayed(const Duration(milliseconds: 250));
}
// A covered route can pause its listeners while the read finishes.
// Retry retired tickets until this provider is disposed.
while (!disposed) {
final ticket = cache.capture(scope, page);
final events = await cache.read(ticket);
if (disposed) return null;
if (!cache.isCurrent(ticket)) continue;
if (events == null) return null;
final preview = await prepare(events);
if (disposed) return null;
if (cache.isCurrent(ticket)) return preview;
}
return null;
}

Future<SavedChannelPreview> _preparePreview(List<NostrEvent> events) =>
Isolate.run(() {
final rows = <NostrEvent>[];
Expand Down Expand Up @@ -82,24 +124,30 @@ final _savedMessageRelayAuthorProvider = FutureProvider<String?>((ref) async {
});

/// Persists only signed events that came from the completed relay read.
Future<void> saveChannelPage(
Future<void> saveMessagePage(
Ref ref,
SavedMessageStore store,
SavedMessageTicket ticket,
List<NostrEvent> events, {
required bool Function() isCurrent,
Future<List<NostrEvent>?> Function()? refreshEvents,
}) async {
try {
final root = await ref.read(savedMessageRootProvider.future);
if (root == null || !isCurrent() || !store.isCurrent(ticket)) return;
// Let the relay timeline paint before copying the page to the worker.
await SchedulerBinding.instance.endOfFrame;
if (!isCurrent() || !store.isCurrent(ticket)) return;
final author = events.isEmpty
final currentEvents = refreshEvents == null
? events
: await refreshEvents();
if (currentEvents == null) return;
if (!isCurrent() || !store.isCurrent(ticket)) return;
final author = currentEvents.isEmpty
? null
: await ref.read(_savedMessageRelayAuthorProvider.future);
if (!isCurrent() || !store.isCurrent(ticket)) return;
await store.save(ticket, events, relayAuthor: author);
await store.save(ticket, currentEvents, relayAuthor: author);
} catch (_) {
// Disk readiness and relay discovery are outside the live timeline path.
}
Expand Down
Loading
Loading