Skip to content

Commit 07da148

Browse files
author
Tryn McCaffery
committed
fix(mobile): reconnect stale relay sessions
Signed-off-by: Tryn McCaffery <[email protected]>
1 parent bcb93f5 commit 07da148

5 files changed

Lines changed: 181 additions & 9 deletions

File tree

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,7 @@ class ComposeBar extends HookConsumerWidget {
495495
);
496496

497497
isSending.value = true;
498+
uploadError.value = null;
498499
try {
499500
if (nonMemberAgentPubkeys.isNotEmpty) {
500501
await ref
@@ -518,6 +519,13 @@ class ComposeBar extends HookConsumerWidget {
518519
if (context.mounted) {
519520
clearComposer();
520521
}
522+
} catch (error) {
523+
// Keep the draft intact and make a missing relay acknowledgement
524+
// visible. An optimistic composer clear is not proof that the relay
525+
// accepted the message.
526+
if (context.mounted) {
527+
uploadError.value = _formatSendError(error);
528+
}
521529
} finally {
522530
if (context.mounted) isSending.value = false;
523531
}
@@ -974,3 +982,10 @@ class ComposeBar extends HookConsumerWidget {
974982
);
975983
}
976984
}
985+
986+
String _formatSendError(Object error) {
987+
if (error is TimeoutException) {
988+
return 'Message wasn\u2019t sent because Buzz did not confirm it. Try again.';
989+
}
990+
return 'Message wasn\u2019t sent. Check your connection and try again.';
991+
}

‎mobile/lib/shared/relay/app_lifecycle_provider.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class AppLifecycleNotifier extends Notifier<AppLifecycleState> {
2020
_connectivitySub = Connectivity().onConnectivityChanged.listen((results) {
2121
final hasNetwork = results.any((r) => r != ConnectivityResult.none);
2222
if (hasNetwork && state == AppLifecycleState.resumed) {
23-
ref.read(relaySessionProvider.notifier).onAppResumed();
23+
ref.read(relaySessionProvider.notifier).onNetworkRestored();
2424
}
2525
});
2626

‎mobile/lib/shared/relay/relay_session.dart‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
103103
int _subIdCounter = 0;
104104
bool _disposed = false;
105105
bool _paused = false;
106+
bool _resumeReconnectRequired = false;
106107
bool _hasConnectedOnce = false;
107108
int _connectionGeneration = 0;
108109

@@ -291,9 +292,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
291292
throw StateError('Relay connection unavailable');
292293
}
293294
if (DateTime.now().isAfter(deadline)) {
294-
throw TimeoutException(
295-
'Relay did not reconnect within $timeout',
296-
);
295+
throw TimeoutException('Relay did not reconnect within $timeout');
297296
}
298297
await Future<void>.delayed(const Duration(milliseconds: 50));
299298
}
@@ -342,6 +341,10 @@ class RelaySessionNotifier extends Notifier<SessionState> {
342341

343342
/// Called by the app lifecycle provider when the app goes to background.
344343
void onAppPaused() {
344+
// Do not trust an iOS socket after any background transition. The process
345+
// may be suspended before the grace timer runs, leaving Dart's local
346+
// socket state as `connected` even though the network path is gone.
347+
_resumeReconnectRequired = true;
345348
_backgroundGraceTimer?.cancel();
346349
_backgroundGraceTimer = Timer(const Duration(seconds: 5), _pauseNow);
347350
}
@@ -361,12 +364,28 @@ class RelaySessionNotifier extends Notifier<SessionState> {
361364
_backgroundGraceTimer?.cancel();
362365
_backgroundGraceTimer = null;
363366

364-
// If still connected, nothing to do — the socket survived the background
365-
// grace window.
366-
if (state.status == SessionStatus.connected) return;
367+
if (!_resumeReconnectRequired && state.status == SessionStatus.connected) {
368+
return;
369+
}
370+
_resumeReconnectRequired = false;
367371

368-
// Cancel any in-flight reconnect backoff timer so we reconnect immediately
369-
// instead of waiting for the (possibly large) exponential delay.
372+
// Reconnect even when the socket still claims to be connected. On iOS a
373+
// backgrounded or path-migrated socket can remain locally open while no
374+
// longer receiving relay events; replacing it is what makes the first
375+
// message after foregrounding observable.
376+
_reconnectTimer?.cancel();
377+
_reconnectDelayMs = _baseReconnectDelayMs;
378+
final config = ref.read(relayConfigProvider);
379+
_connect(config);
380+
}
381+
382+
/// Replace the socket immediately after the network becomes reachable.
383+
///
384+
/// Connectivity restoration is stronger evidence than the websocket's
385+
/// local state: a half-open socket may still report connected after Wi-Fi,
386+
/// cellular, VPN, or Tailnet path migration.
387+
void onNetworkRestored() {
388+
if (_disposed || _paused) return;
370389
_reconnectTimer?.cancel();
371390
_reconnectDelayMs = _baseReconnectDelayMs;
372391
final config = ref.read(relayConfigProvider);

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,37 @@ void main() {
393393
});
394394

395395
group('ComposeBar', () {
396+
testWidgets('failed send keeps the draft and shows a truthful error', (
397+
tester,
398+
) async {
399+
await tester.pumpWidget(
400+
_buildComposeBar(
401+
uploadService: _testUploadService(nostr.Keys.generate().nsec),
402+
onSend:
403+
(
404+
content,
405+
mentionPubkeys, {
406+
mediaTags = const <List<String>>[],
407+
}) async {
408+
throw TimeoutException('relay acknowledgement missing');
409+
},
410+
),
411+
);
412+
413+
await _expandComposer(tester);
414+
await tester.enterText(find.byType(TextField), 'please persist');
415+
await tester.tap(find.byIcon(LucideIcons.arrowUp));
416+
await tester.pump();
417+
418+
expect(find.text('please persist'), findsOneWidget);
419+
expect(
420+
find.text(
421+
'Message wasn\u2019t sent because Buzz did not confirm it. Try again.',
422+
),
423+
findsOneWidget,
424+
);
425+
});
426+
396427
testWidgets('mounted composer does not carry draft text across an in-place '
397428
'identity switch', (tester) async {
398429
final keysA = nostr.Keys.generate();

‎mobile/test/shared/relay/relay_session_test.dart‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,113 @@ void main() {
260260
expect(session.state.status, SessionStatus.disconnected);
261261
});
262262

263+
test(
264+
'foreground replaces a socket that still claims to be connected',
265+
() async {
266+
final sockets = <_ControlledRelaySocket>[];
267+
final keychain = nostr.Keys.generate();
268+
final session = RelaySessionNotifier(
269+
socketFactory:
270+
({
271+
required wsUrl,
272+
required nsec,
273+
required onMessage,
274+
required onConnected,
275+
required onDisconnected,
276+
}) {
277+
final socket = _ControlledRelaySocket(
278+
wsUrl: wsUrl,
279+
nsec: nsec,
280+
onMessage: onMessage,
281+
onConnected: onConnected,
282+
onDisconnected: onDisconnected,
283+
);
284+
sockets.add(socket);
285+
return socket;
286+
},
287+
);
288+
final container = ProviderContainer(
289+
overrides: [
290+
relaySessionProvider.overrideWith(() => session),
291+
relayConfigProvider.overrideWith(
292+
() => _FakeRelayConfigNotifier(
293+
baseUrl: 'https://relay.example',
294+
nsec: keychain.nsec,
295+
),
296+
),
297+
authProvider.overrideWith(() => _AuthenticatedAuthNotifier()),
298+
],
299+
);
300+
addTearDown(container.dispose);
301+
await container.read(authProvider.future);
302+
final subscription = container.listen(relaySessionProvider, (_, _) {});
303+
addTearDown(subscription.close);
304+
await Future<void>.delayed(Duration.zero);
305+
306+
sockets.single.connectSuccessfully();
307+
expect(session.state.status, SessionStatus.connected);
308+
309+
session.onAppPaused();
310+
session.onAppResumed();
311+
await Future<void>.delayed(Duration.zero);
312+
313+
expect(sockets, hasLength(2));
314+
expect(session.state.status, SessionStatus.reconnecting);
315+
sockets.last.connectSuccessfully();
316+
expect(session.state.status, SessionStatus.connected);
317+
},
318+
);
319+
320+
test('network restoration replaces a half-open connected socket', () async {
321+
final sockets = <_ControlledRelaySocket>[];
322+
final keychain = nostr.Keys.generate();
323+
final session = RelaySessionNotifier(
324+
socketFactory:
325+
({
326+
required wsUrl,
327+
required nsec,
328+
required onMessage,
329+
required onConnected,
330+
required onDisconnected,
331+
}) {
332+
final socket = _ControlledRelaySocket(
333+
wsUrl: wsUrl,
334+
nsec: nsec,
335+
onMessage: onMessage,
336+
onConnected: onConnected,
337+
onDisconnected: onDisconnected,
338+
);
339+
sockets.add(socket);
340+
return socket;
341+
},
342+
);
343+
final container = ProviderContainer(
344+
overrides: [
345+
relaySessionProvider.overrideWith(() => session),
346+
relayConfigProvider.overrideWith(
347+
() => _FakeRelayConfigNotifier(
348+
baseUrl: 'https://relay.example',
349+
nsec: keychain.nsec,
350+
),
351+
),
352+
authProvider.overrideWith(() => _AuthenticatedAuthNotifier()),
353+
],
354+
);
355+
addTearDown(container.dispose);
356+
await container.read(authProvider.future);
357+
final subscription = container.listen(relaySessionProvider, (_, _) {});
358+
addTearDown(subscription.close);
359+
await Future<void>.delayed(Duration.zero);
360+
361+
sockets.single.connectSuccessfully();
362+
session.onNetworkRestored();
363+
await Future<void>.delayed(Duration.zero);
364+
365+
expect(sockets, hasLength(2));
366+
sockets.last.connectSuccessfully();
367+
expect(session.state.status, SessionStatus.connected);
368+
});
369+
263370
test('delivers the same live event to each matching subscription', () async {
264371
final session = RelaySessionNotifier();
265372
final firstEvents = <NostrEvent>[];

0 commit comments

Comments
 (0)