Skip to content

Commit ef2aa1a

Browse files
authored
fix(mobile): preserve thread replies through refresh failures (#7757)
## Summary A failed mobile thread refresh could briefly remove replies and show “0 replies” even though Riverpod still retained the previous result. Read the retained reply value directly and merge it with pending local replies through errors and retries. When a reopened thread has no retained result, show loading or failure instead of a false zero count. Error status remains visible alongside retained replies. No additional cache or retention is introduced. Current main intentionally disposes thread queries on close; reopening still fetches fresh data. The recorded symptom is reproduced by the failed-refresh test, but the recording alone does not establish its network trigger. ### Related issue Related to #4831 (thread refresh and disposal behavior), incorporated into main through #6691. No duplicate for this rendering defect found. ### Testing - Reproduced disappearing cached replies in widget tests before the fix; the new retry/recovery, terminal-error, reopen/loading, initial-error, and empty-result tests now pass. - Provider coverage verifies cached and pending local replies survive a failed refresh and confirmation still clears the local overlay. - All five new widget regressions, the existing hydration/scroll-position regression, all nine thread-provider tests, Flutter analysis, and the final-head full mobile pre-push gate passed (2,261 tests passed; four skipped). - Phone-width and large-text rendering checked with synthetic messages. [Before/after screenshots](#7757 (comment)). - All final-head GitHub checks passed, including mobile tests, Android debug APK, iOS simulator app, and unsigned iOS release builds. - Codex code review and security review are clean for `4e5f606ae`; the earlier accessibility finding is fixed and resolved. Builderbot review was requested but has not returned a result. - Broad local `just ci` could not finish: unchanged ACP timing tests failed, including `keepalive_resets_idle_past_deadline` on the lower-concurrency retry. The separate ACP run passed all 941 tests. Initial parallel mobile runs also hit timing flakes; the final-head full mobile gate passed. No unrelated native code was changed. --------- Signed-off-by: Tom Brow <[email protected]>
1 parent 4ee9f8b commit ef2aa1a

6 files changed

Lines changed: 286 additions & 20 deletions

File tree

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

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -128,14 +128,15 @@ class ThreadDetailPage extends HookConsumerWidget {
128128
final liveChannelEvents =
129129
ref.watch(channelMessagesProvider(channelId)).value ??
130130
const <NostrEvent>[];
131-
final replyMessages = repliesState.whenData((events) {
132-
return formatTimeline(
133-
mergeThreadEvents(events, liveChannelEvents),
134-
currentPubkey: currentPubkey,
135-
);
136-
});
137-
138-
final fetchedReplies = replyMessages.value;
131+
// Loading/error states can still carry replies from the last query.
132+
// whenData drops that retained value during retries.
133+
final replyEvents = repliesState.value;
134+
final fetchedReplies = replyEvents == null
135+
? null
136+
: formatTimeline(
137+
mergeThreadEvents(replyEvents, liveChannelEvents),
138+
currentPubkey: currentPubkey,
139+
);
139140
final hasFetchedReplies = fetchedReplies != null;
140141
// A terminal query error cannot produce a more authoritative list. Keep
141142
// loading states provisional, but let the hydrated route snapshot drive
@@ -892,6 +893,7 @@ class ThreadDetailPage extends HookConsumerWidget {
892893
itemPositionsListener: itemPositionsListener,
893894
bottomInset: timelineBottomInset,
894895
replies: replies,
896+
relayReplyState: relayReplyState,
895897
localSendAnimations: localSendAnimations,
896898
trackActiveScrollPosition: trackActiveScrollPosition,
897899
headIsDeleted: liveDeletionHidesHead,

‎mobile/lib/features/channels/thread_detail_page/message_list.dart‎

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ class _ThreadMessageList extends StatelessWidget {
99
final ItemPositionsListener itemPositionsListener;
1010
final double bottomInset;
1111
final List<TimelineMessage> replies;
12+
final AsyncValue<List<NostrEvent>> relayReplyState;
1213
final Map<String, DateTime> localSendAnimations;
1314
final Widget Function(Widget child) trackActiveScrollPosition;
1415
final bool headIsDeleted;
@@ -34,6 +35,7 @@ class _ThreadMessageList extends StatelessWidget {
3435
required this.itemPositionsListener,
3536
required this.bottomInset,
3637
required this.replies,
38+
required this.relayReplyState,
3739
required this.localSendAnimations,
3840
required this.trackActiveScrollPosition,
3941
required this.headIsDeleted,
@@ -51,6 +53,18 @@ class _ThreadMessageList extends StatelessWidget {
5153
required this.childrenByParent,
5254
});
5355

56+
String get _replySummary {
57+
if (!relayReplyState.hasValue && replies.isEmpty) {
58+
return relayReplyState.isLoading
59+
? 'Loading replies…'
60+
: 'Couldn’t load replies';
61+
}
62+
final count =
63+
'${replies.length} ${replies.length == 1 ? 'reply' : 'replies'}';
64+
if (!relayReplyState.hasError) return count;
65+
return '$count · ${relayReplyState.isLoading ? 'Retrying…' : 'Couldn’t refresh'}';
66+
}
67+
5468
@override
5569
Widget build(BuildContext context) {
5670
const headIndex = 0;
@@ -136,13 +150,19 @@ class _ThreadMessageList extends StatelessWidget {
136150
),
137151
child: Row(
138152
children: [
139-
Text(
140-
'${replies.length} ${replies.length == 1 ? 'reply' : 'replies'}',
141-
style: context.textTheme.labelMedium
142-
?.copyWith(
143-
color: context.colors.onSurfaceVariant,
144-
fontWeight: FontWeight.w600,
145-
),
153+
Flexible(
154+
child: Semantics(
155+
liveRegion: true,
156+
child: Text(
157+
_replySummary,
158+
style: context.textTheme.labelMedium
159+
?.copyWith(
160+
color:
161+
context.colors.onSurfaceVariant,
162+
fontWeight: FontWeight.w600,
163+
),
164+
),
165+
),
146166
),
147167
const SizedBox(width: Grid.xxs),
148168
Expanded(

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

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -130,11 +130,10 @@ final threadRepliesWithLocalProvider = Provider.autoDispose
130130
}
131131
}
132132
if (localReplies.isEmpty) return relayReplies;
133-
return relayReplies.when(
134-
data: (events) => AsyncData(_mergeReplies(events, localReplies)),
135-
loading: () => AsyncData(localReplies),
136-
error: (error, stackTrace) => AsyncData(localReplies),
137-
);
133+
// This provider supplies display events; the original query remains
134+
// the source of loading/error status. Preserve its retained value when
135+
// merging optimistic replies during a failed refresh or retry.
136+
return AsyncData(_mergeReplies(authoritative ?? const [], localReplies));
138137
});
139138

140139
/// Union two event lists by id, newest-wins, in timeline order.

‎mobile/test/features/channels/channel_detail_page_test.dart‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ import 'package:buzz/shared/widgets/masked_avatar_badge.dart';
6464
import 'package:buzz/shared/widgets/skeleton.dart';
6565
import 'package:shared_preferences/shared_preferences.dart';
6666

67+
part 'thread_reply_refresh_cases.dart';
68+
6769
const _channelId = '11111111-2222-4333-8444-555555555555';
6870
const _huddleChannelId = '8d764100-fd8f-44cf-9c98-6d8fbd739b8c';
6971
const _otherChannelId = '22222222-3333-4444-8555-666666666666';
@@ -471,6 +473,7 @@ double? effectiveFontSizeForText(
471473
}
472474

473475
void main() {
476+
threadReplyRefreshTests();
474477
setUp(() async {
475478
SharedPreferences.setMockInitialValues({});
476479
_testPrefs = await SharedPreferences.getInstance();

‎mobile/test/features/channels/thread_replies_provider_test.dart‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,53 @@ void main() {
215215
},
216216
);
217217

218+
test(
219+
'local replies preserve cached authoritative replies after refresh failure',
220+
() async {
221+
final cached = _reply('cached', 1000);
222+
final local = _reply('local', 1001);
223+
final session = _FakeRelaySession()..replies = [cached];
224+
final container = ProviderContainer(
225+
retry: (_, _) => null,
226+
overrides: [relaySessionProvider.overrideWith(() => session)],
227+
);
228+
addTearDown(container.dispose);
229+
final combined = container.listen(
230+
threadRepliesWithLocalProvider(args),
231+
(_, _) {},
232+
);
233+
await container.read(threadRepliesProvider(args).future);
234+
container.read(threadLocalRepliesProvider(args).notifier).add(local);
235+
await container.pump();
236+
final refresh = Completer<List<NostrEvent>>();
237+
session.nextQueryGate = refresh;
238+
container.invalidate(threadRepliesProvider(args));
239+
await container.pump();
240+
expect(combined.read().value?.map((event) => event.id), [
241+
'cached',
242+
'local',
243+
]);
244+
refresh.completeError(Exception('Refresh failed'));
245+
await container.pump();
246+
expect(container.read(threadRepliesProvider(args)).hasError, isTrue);
247+
expect(combined.read().value?.map((event) => event.id), [
248+
'cached',
249+
'local',
250+
]);
251+
expect(container.read(threadLocalRepliesProvider(args)), [local]);
252+
session.replies = [cached, local];
253+
container.invalidate(threadRepliesProvider(args));
254+
await container.read(threadRepliesProvider(args).future);
255+
await container.pump();
256+
expect(combined.read().value?.map((event) => event.id), [
257+
'cached',
258+
'local',
259+
]);
260+
await Future<void>.delayed(Duration.zero);
261+
expect(container.read(threadLocalRepliesProvider(args)), isEmpty);
262+
},
263+
);
264+
218265
test('reopening a disposed thread performs a fresh load', () async {
219266
final (container, fakeSession, subscription) = makeHarness([
220267
_reply('r1', 1000),
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
part of 'channel_detail_page_test.dart';
2+
3+
void threadReplyRefreshTests() {
4+
const args = ThreadRepliesArgs(channelId: _channelId, rootId: 'refresh-root');
5+
final root = _textMsg(
6+
id: args.rootId,
7+
pubkey: 'alice',
8+
content: 'Refresh root',
9+
);
10+
final reply = _textMsg(
11+
id: 'cached-reply',
12+
pubkey: 'bob',
13+
content: 'Cached reply',
14+
createdAt: 1001,
15+
extraTags: [
16+
['e', args.rootId, '', 'reply'],
17+
],
18+
);
19+
20+
Future<(NavigatorState, ProviderContainer)> mount(
21+
WidgetTester tester,
22+
Future<List<NostrEvent>> Function() load, {
23+
bool retry = false,
24+
TextScaler textScaler = TextScaler.noScaling,
25+
}) async {
26+
await tester.pumpWidget(
27+
_buildTestable(
28+
messages: [root],
29+
textScaler: textScaler,
30+
threadReplyLoaders: {args.rootId: load},
31+
providerRetry: (_, _) =>
32+
retry ? const Duration(milliseconds: 200) : null,
33+
),
34+
);
35+
await tester.pumpAndSettle();
36+
final context = tester.element(find.byType(ChannelDetailPage));
37+
return (Navigator.of(context), ProviderScope.containerOf(context));
38+
}
39+
40+
void open(NavigatorState navigator) {
41+
final head = formatTimeline([root]).single;
42+
navigator.push(
43+
MaterialPageRoute<void>(
44+
builder: (_) => ThreadDetailPage(
45+
threadHead: head,
46+
allMessages: [head],
47+
channelId: _channelId,
48+
currentPubkey: 'self',
49+
isMember: true,
50+
isArchived: false,
51+
),
52+
),
53+
);
54+
}
55+
56+
testWidgets(
57+
'thread refresh keeps cached replies through retry and recovery',
58+
(tester) async {
59+
var calls = 0;
60+
final refresh = Completer<List<NostrEvent>>();
61+
final retry = Completer<List<NostrEvent>>();
62+
final (navigator, container) = await mount(tester, () {
63+
calls++;
64+
return switch (calls) {
65+
1 => Future.value([reply]),
66+
2 => refresh.future,
67+
_ => retry.future,
68+
};
69+
}, retry: true);
70+
open(navigator);
71+
await tester.pumpAndSettle();
72+
expect(find.text('1 reply'), findsOneWidget);
73+
container.invalidate(threadRepliesProvider(args));
74+
await tester.pump();
75+
expect(find.text('1 reply'), findsOneWidget);
76+
refresh.completeError(Exception('Transient refresh failure'));
77+
await tester.pump();
78+
for (var frame = 0; frame < 20; frame++) {
79+
await tester.pump(const Duration(milliseconds: 16));
80+
expect(find.text('0 replies'), findsNothing, reason: 'frame $frame');
81+
expect(
82+
find.byKey(const ValueKey('thread-message-group-cached-reply')),
83+
findsOneWidget,
84+
);
85+
expect(container.read(threadRepliesProvider(args)).value, [reply]);
86+
}
87+
expect(calls, 3);
88+
retry.complete([
89+
reply,
90+
_textMsg(
91+
id: 'fresh-reply',
92+
pubkey: 'bob',
93+
content: 'Fresh reply',
94+
createdAt: 1002,
95+
extraTags: [
96+
['e', args.rootId, '', 'reply'],
97+
],
98+
),
99+
]);
100+
await tester.pumpAndSettle();
101+
expect(find.text('2 replies'), findsOneWidget);
102+
expect(
103+
find.byKey(const ValueKey('thread-message-group-fresh-reply')),
104+
findsOneWidget,
105+
);
106+
},
107+
);
108+
109+
testWidgets('thread refresh error keeps cached replies visible', (
110+
tester,
111+
) async {
112+
final semantics = tester.ensureSemantics();
113+
var calls = 0;
114+
final refresh = Completer<List<NostrEvent>>();
115+
tester.view.physicalSize = const Size(320, 844);
116+
tester.view.devicePixelRatio = 1;
117+
addTearDown(tester.view.resetPhysicalSize);
118+
addTearDown(tester.view.resetDevicePixelRatio);
119+
final (navigator, container) = await mount(
120+
tester,
121+
() => ++calls == 1 ? Future.value([reply]) : refresh.future,
122+
textScaler: const TextScaler.linear(2),
123+
);
124+
open(navigator);
125+
await tester.pumpAndSettle();
126+
container.invalidate(threadRepliesProvider(args));
127+
await tester.pump();
128+
refresh.completeError(Exception('Refresh failed'));
129+
await tester.pumpAndSettle();
130+
expect(
131+
find.byKey(const ValueKey('thread-message-group-cached-reply')),
132+
findsOneWidget,
133+
);
134+
expect(find.text('0 replies'), findsNothing);
135+
expect(find.text('1 reply · Couldn’t refresh'), findsOneWidget);
136+
expect(
137+
tester
138+
.getSemantics(find.text('1 reply · Couldn’t refresh'))
139+
.getSemanticsData()
140+
.flagsCollection
141+
.isLiveRegion,
142+
isTrue,
143+
);
144+
expect(tester.takeException(), isNull);
145+
expect(container.read(threadRepliesProvider(args)).hasError, isTrue);
146+
semantics.dispose();
147+
});
148+
149+
testWidgets('thread reopen shows loading until the fresh query completes', (
150+
tester,
151+
) async {
152+
var calls = 0;
153+
final reopened = Completer<List<NostrEvent>>();
154+
final (navigator, _) = await mount(
155+
tester,
156+
() => ++calls == 1 ? Future.value([reply]) : reopened.future,
157+
);
158+
open(navigator);
159+
await tester.pumpAndSettle();
160+
navigator.pop();
161+
await tester.pumpAndSettle();
162+
open(navigator);
163+
await tester.pumpAndSettle();
164+
expect(calls, 2);
165+
expect(find.text('0 replies'), findsNothing);
166+
expect(find.text('Loading replies…'), findsOneWidget);
167+
reopened.complete([reply]);
168+
await tester.pumpAndSettle();
169+
expect(find.text('1 reply'), findsOneWidget);
170+
expect(find.text('Loading replies…'), findsNothing);
171+
});
172+
173+
testWidgets('thread initial error is distinct from an empty thread', (
174+
tester,
175+
) async {
176+
final query = Completer<List<NostrEvent>>();
177+
final (navigator, _) = await mount(tester, () => query.future);
178+
open(navigator);
179+
await tester.pumpAndSettle();
180+
query.completeError(Exception('Initial load failed'));
181+
await tester.pumpAndSettle();
182+
expect(find.text('0 replies'), findsNothing);
183+
expect(find.text('Couldn’t load replies'), findsOneWidget);
184+
});
185+
testWidgets('thread successful empty query displays zero replies', (
186+
tester,
187+
) async {
188+
final (navigator, _) = await mount(tester, () async => []);
189+
open(navigator);
190+
await tester.pumpAndSettle();
191+
expect(find.text('0 replies'), findsOneWidget);
192+
expect(find.text('Loading replies…'), findsNothing);
193+
expect(find.text('Couldn’t load replies'), findsNothing);
194+
});
195+
}

0 commit comments

Comments
 (0)