Skip to content

Commit ce56e34

Browse files
brownpub1tquskdu6yc4h8l7xxtceculxw600grekeq0xg2ukqfrwl7vrzg3quz3gmp
andauthored
fix(mobile): recover stale relay sessions (block#4372)
### Summary Fixes [this issue](buzz://message?channel=e62570dd-33ad-42c5-b92b-75f2689f9694&id=b726c366abfe62429ee3cdcd34d0c0fb98c33c3ea053480585bed71745412b56): > I often don’t see my bot responses until after I post. they’re usually time stamped correctly so I think it’s just a refresh issue? ### What changed? Buzz Mobile now reconnects relay sessions after the app has remained backgrounded beyond the existing 5-second grace period, even when the session still reports a stale `connected` state. This makes resume recovery independent of whether iOS runs the grace timer before or after delivering `resumed`. Reconnection is now based on elapsed background time rather than a direct socket-health probe. - If the app was backgrounded for at least the 5-second grace period, the socket is presumed dead and the session reconnects regardless of reported status. - If it was backgrounded for less than that, a reported `connected` status is still trusted. In the sub-5-second window the socket is either genuinely alive, which is the common case for a momentary background, or it is dead and the client ping detects it within the two-interval worst case described below. That is now a degraded-latency path, not a silent-forever path. The mobile relay socket now uses `IOWebSocketChannel.connect` with a 30-second `pingInterval`. An unanswered ping closes the Dart socket through the existing disconnect and reconnect path. Detection takes up to two ping intervals, so about 60 seconds worst case, not 30. One interval of idleness elapses and a ping is sent, then a second interval elapses with no pong and the socket closes. Any inbound pong restarts the first stage, so the clock measures idleness rather than running on a fixed cadence. ### Why? Buzz iOS can sometimes stop showing new bot or agent responses after a phone has been locked for 5 to 10 minutes. When the user later posts a message, the missing responses can appear all at once. iOS may suspend Buzz before the short delayed cleanup that would normally close its connection has a chance to run. Before this change, Buzz trusted the resulting stale healthy status on resume and skipped reconnecting, so the missing responses stayed hidden until a later post exposed the dead connection. A state-machine test with a stubbed connection reproduced this reported pattern and showed that it matches this failure mode: the failed post triggered a reconnect that fetched the missing messages. The same test also checked the other candidate explanation, the bug tracked in [block#3053](block#3053), where the relay has closed the app's subscription. That state does not produce the pattern. Posting succeeds and the user's own message appears, but nothing looks for the missed messages, so they stay hidden. The test confirmed that the missed messages were still available to fetch in that state, so the missing step was a trigger to fetch them. This was not an end-to-end reproduction on an iOS device or a live relay. The new resume check covers the normal lock and unlock path. If the app was backgrounded for less than the 5-second grace period, it still trusts a connection marked as healthy. A dead connection in that window is instead detected by the ping check, which can take up to about 60 seconds but prevents the app from remaining silently stuck. The ping only runs while iOS is running the app, so it does not detect a connection that died during suspension; the resume check owns the lock and unlock path. A pre-existing path also runs the same resume handling when network connectivity returns while the app is already in the foreground. Because the app was not backgrounded, this change does not alter that path, which still trusts a connection marked as healthy and relies on the slower ping check. Recovery from a subscription that the relay explicitly closes remains in [block#3053](block#3053), and the two changes overlap in one file. Changes to how missed messages are backfilled or replayed are out of scope. ### How is it tested? Full mobile suite at base and head. Both runs have the same known macOS-host-only failure in `ChannelDetailPage keeps follow mode off while a tall newest message stays visible` at line 1053: - Base: 1,021 passed, 1 skipped, 1 failed - Head: 1,025 passed, 1 skipped, 1 failed Added tests: - [`relay_session_test.dart`](https://github.com/block/buzz/tree/main/mobile/test/shared/relay/relay_session_test.dart): long-background resume reconnect and within-grace control - [`relay_socket_liveness_test.dart`](https://github.com/block/buzz/tree/main/mobile/test/shared/relay/relay_socket_liveness_test.dart): silent-peer disconnect and idle-but-healthy control Mutation checks confirm that removing elapsed-background resume recovery fails with one socket instead of two, and removing `pingInterval` leaves the silent peer connected. Restored production code passes both mutations' regression tests and the healthy idle control. Signed-off-by: Tom Brow <[email protected]> Co-authored-by: npub1tquskdu6yc4h8l7xxtceculxw600grekeq0xg2ukqfrwl7vrzg3quz3gmp <58390b379a262b73ffc632f19c73e6769ef40f36c81e642b960246eff9831222@buzz.block.builderlab.xyz>
1 parent 651f637 commit ce56e34

6 files changed

Lines changed: 259 additions & 7 deletions

File tree

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

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,17 +89,20 @@ class RelaySessionNotifier extends Notifier<SessionState> {
8989
RelaySessionNotifier({
9090
http.Client? httpClient,
9191
RelaySocketFactory socketFactory = RelaySocket.new,
92+
DateTime Function()? now,
9293
RelayRateLimitGate? rateLimitGate,
9394
RelayTimerFactory retryTimerFactory = Timer.new,
9495
Future<void> Function(Duration) replayDelay = Future.delayed,
9596
}) : _httpClient = httpClient,
9697
_socketFactory = socketFactory,
98+
_now = now ?? DateTime.now,
9799
_rateLimitGate = rateLimitGate ?? RelayRateLimitGate(),
98100
_retryTimerFactory = retryTimerFactory,
99101
_replayDelay = replayDelay;
100102

101103
final http.Client? _httpClient;
102104
final RelaySocketFactory _socketFactory;
105+
final DateTime Function() _now;
103106
final RelayRateLimitGate _rateLimitGate;
104107
final RelayTimerFactory _retryTimerFactory;
105108
final Future<void> Function(Duration) _replayDelay;
@@ -111,6 +114,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
111114
static const _replayBatchSize = 8;
112115
static const _replayInterBatchDelay = Duration(milliseconds: 50);
113116
static const _maxRecentDeliveryKeys = 5000;
117+
static const _backgroundGraceDuration = Duration(seconds: 5);
114118

115119
RelaySocket? _socket;
116120
final Map<String, _HistorySubscription> _historySubscriptions = {};
@@ -122,6 +126,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
122126
Timer? _reconnectTimer;
123127
Timer? _flushTimer;
124128
Timer? _backgroundGraceTimer;
129+
DateTime? _backgroundedAt;
125130
int _reconnectDelayMs = _baseReconnectDelayMs;
126131
int _subIdCounter = 0;
127132
bool _disposed = false;
@@ -394,8 +399,9 @@ class RelaySessionNotifier extends Notifier<SessionState> {
394399

395400
/// Called by the app lifecycle provider when the app goes to background.
396401
void onAppPaused() {
402+
_backgroundedAt = _now();
397403
_backgroundGraceTimer?.cancel();
398-
_backgroundGraceTimer = Timer(const Duration(seconds: 5), _pauseNow);
404+
_backgroundGraceTimer = Timer(_backgroundGraceDuration, _pauseNow);
399405
}
400406

401407
void _pauseNow() {
@@ -411,12 +417,18 @@ class RelaySessionNotifier extends Notifier<SessionState> {
411417
/// Called by the app lifecycle provider when the app returns to foreground.
412418
void onAppResumed() {
413419
_paused = false;
420+
final backgroundedAt = _backgroundedAt;
421+
_backgroundedAt = null;
414422
_backgroundGraceTimer?.cancel();
415423
_backgroundGraceTimer = null;
416424

417-
// If still connected, nothing to do — the socket survived the background
418-
// grace window.
419-
if (state.status == SessionStatus.connected) return;
425+
final backgroundedLongEnoughToRequireReconnect =
426+
backgroundedAt != null &&
427+
_now().difference(backgroundedAt) >= _backgroundGraceDuration;
428+
if (!backgroundedLongEnoughToRequireReconnect &&
429+
state.status == SessionStatus.connected) {
430+
return;
431+
}
420432

421433
// Cancel any in-flight reconnect backoff timer so we reconnect immediately
422434
// instead of waiting for the (possibly large) exponential delay.
@@ -908,6 +920,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
908920
_reconnectTimer?.cancel();
909921
_flushTimer?.cancel();
910922
_backgroundGraceTimer?.cancel();
923+
_backgroundedAt = null;
911924
_cancelAllClosedRetries();
912925
_rateLimitGate.reset();
913926
_visibleChannelsByOwner.clear();

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import 'dart:convert';
33

44
import 'package:flutter/foundation.dart';
55
import 'package:nostr/nostr.dart' as nostr;
6+
import 'package:web_socket_channel/io.dart';
67
import 'package:web_socket_channel/web_socket_channel.dart';
78

89
import 'nostr_models.dart';
@@ -30,6 +31,12 @@ Exception classifyRelayAuthFailure(String message) {
3031
}
3132

3233
class RelaySocket {
34+
/// Interval for sending a ping and awaiting its pong before disconnecting.
35+
static const pingInterval = Duration(seconds: 30);
36+
37+
@visibleForTesting
38+
static Duration debugPingInterval = pingInterval;
39+
3340
final String _wsUrl;
3441
final String? _nsec;
3542
final void Function(List<dynamic> message) _onMessage;
@@ -63,7 +70,10 @@ class RelaySocket {
6370
_state = SocketState.connecting;
6471

6572
try {
66-
_channel = WebSocketChannel.connect(Uri.parse(_wsUrl));
73+
_channel = IOWebSocketChannel.connect(
74+
Uri.parse(_wsUrl),
75+
pingInterval: debugPingInterval,
76+
);
6777
await _channel!.ready;
6878
} catch (e) {
6979
_state = SocketState.disconnected;

‎mobile/pubspec.lock‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ packages:
274274
source: hosted
275275
version: "0.3.5+2"
276276
crypto:
277-
dependency: transitive
277+
dependency: "direct dev"
278278
description:
279279
name: crypto
280280
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf

‎mobile/pubspec.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ dev_dependencies:
4747
flutter_test:
4848
sdk: flutter
4949
flutter_lints: ^6.0.0
50+
crypto: ^3.0.7
5051
custom_lint: ^0.8.0
5152
riverpod_lint: ^3.1.0
5253
mocktail: ^1.0.4

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

Lines changed: 118 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,120 @@ void main() {
432432
expect(session.state.status, SessionStatus.disconnected);
433433
});
434434

435+
test(
436+
'resume reconnects a stale connected session after a long pause',
437+
() async {
438+
final sockets = <_ControlledRelaySocket>[];
439+
final keychain = nostr.Keys.generate();
440+
var now = DateTime(2026, 8, 2, 12);
441+
final session = RelaySessionNotifier(
442+
now: () => now,
443+
socketFactory:
444+
({
445+
required wsUrl,
446+
required nsec,
447+
required onMessage,
448+
required onConnected,
449+
required onDisconnected,
450+
}) {
451+
final socket = _ControlledRelaySocket(
452+
wsUrl: wsUrl,
453+
nsec: nsec,
454+
onMessage: onMessage,
455+
onConnected: onConnected,
456+
onDisconnected: onDisconnected,
457+
);
458+
sockets.add(socket);
459+
return socket;
460+
},
461+
);
462+
final container = ProviderContainer(
463+
overrides: [
464+
relaySessionProvider.overrideWith(() => session),
465+
relayConfigProvider.overrideWith(
466+
() => _FakeRelayConfigNotifier(
467+
baseUrl: 'https://relay.example',
468+
nsec: keychain.nsec,
469+
),
470+
),
471+
authProvider.overrideWith(() => _AuthenticatedAuthNotifier()),
472+
],
473+
);
474+
addTearDown(container.dispose);
475+
await container.read(authProvider.future);
476+
final subscription = container.listen(relaySessionProvider, (_, _) {});
477+
addTearDown(subscription.close);
478+
await Future<void>.delayed(Duration.zero);
479+
sockets.single.connectSuccessfully();
480+
481+
session.onAppPaused();
482+
now = now.add(const Duration(minutes: 5));
483+
session.onAppResumed();
484+
await Future<void>.delayed(Duration.zero);
485+
486+
expect(sockets, hasLength(2));
487+
expect(sockets.first.disposeCalls, 1);
488+
expect(session.state.status, SessionStatus.reconnecting);
489+
},
490+
);
491+
492+
test(
493+
'resume keeps a connected session within the background grace period',
494+
() async {
495+
final sockets = <_ControlledRelaySocket>[];
496+
final keychain = nostr.Keys.generate();
497+
var now = DateTime(2026, 8, 2, 12);
498+
final session = RelaySessionNotifier(
499+
now: () => now,
500+
socketFactory:
501+
({
502+
required wsUrl,
503+
required nsec,
504+
required onMessage,
505+
required onConnected,
506+
required onDisconnected,
507+
}) {
508+
final socket = _ControlledRelaySocket(
509+
wsUrl: wsUrl,
510+
nsec: nsec,
511+
onMessage: onMessage,
512+
onConnected: onConnected,
513+
onDisconnected: onDisconnected,
514+
);
515+
sockets.add(socket);
516+
return socket;
517+
},
518+
);
519+
final container = ProviderContainer(
520+
overrides: [
521+
relaySessionProvider.overrideWith(() => session),
522+
relayConfigProvider.overrideWith(
523+
() => _FakeRelayConfigNotifier(
524+
baseUrl: 'https://relay.example',
525+
nsec: keychain.nsec,
526+
),
527+
),
528+
authProvider.overrideWith(() => _AuthenticatedAuthNotifier()),
529+
],
530+
);
531+
addTearDown(container.dispose);
532+
await container.read(authProvider.future);
533+
final subscription = container.listen(relaySessionProvider, (_, _) {});
534+
addTearDown(subscription.close);
535+
await Future<void>.delayed(Duration.zero);
536+
sockets.single.connectSuccessfully();
537+
538+
session.onAppPaused();
539+
now = now.add(const Duration(seconds: 4));
540+
session.onAppResumed();
541+
await Future<void>.delayed(Duration.zero);
542+
543+
expect(sockets, hasLength(1));
544+
expect(sockets.single.disposeCalls, 0);
545+
expect(session.state.status, SessionStatus.connected);
546+
},
547+
);
548+
435549
test('delivers the same live event to each matching subscription', () async {
436550
final session = RelaySessionNotifier();
437551
final firstEvents = <NostrEvent>[];
@@ -1143,6 +1257,7 @@ class _AuthenticatedAuthNotifier extends AuthNotifier {
11431257
class _ControlledRelaySocket extends RelaySocket {
11441258
final void Function() _connected;
11451259
final void Function(Object? error) _disconnected;
1260+
int disposeCalls = 0;
11461261

11471262
_ControlledRelaySocket({
11481263
required super.wsUrl,
@@ -1157,7 +1272,9 @@ class _ControlledRelaySocket extends RelaySocket {
11571272
Future<void> connect() async {}
11581273

11591274
@override
1160-
void dispose() {}
1275+
void dispose() {
1276+
disposeCalls++;
1277+
}
11611278

11621279
void connectSuccessfully() => _connected();
11631280

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import 'dart:async';
2+
import 'dart:convert';
3+
import 'dart:io';
4+
5+
import 'package:buzz/shared/relay/relay_socket.dart';
6+
import 'package:crypto/crypto.dart';
7+
import 'package:flutter_test/flutter_test.dart';
8+
9+
/// A server that completes the WS handshake then never speaks again: no pongs,
10+
/// no close frame. Only a client-side ping timeout can notice.
11+
Future<ServerSocket> _silentAfterHandshakeServer() async {
12+
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
13+
server.listen((client) {
14+
client.listen(
15+
(data) {
16+
final match = RegExp(
17+
r'Sec-WebSocket-Key: (.*)\r\n',
18+
caseSensitive: false,
19+
).firstMatch(String.fromCharCodes(data));
20+
if (match == null) return;
21+
final accept = base64.encode(
22+
sha1
23+
.convert(
24+
utf8.encode(
25+
'${match.group(1)!.trim()}258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
26+
),
27+
)
28+
.bytes,
29+
);
30+
client.write(
31+
'HTTP/1.1 101 Switching Protocols\r\n'
32+
'Upgrade: websocket\r\nConnection: Upgrade\r\n'
33+
'Sec-WebSocket-Accept: $accept\r\n\r\n',
34+
);
35+
},
36+
onError: (_) {},
37+
onDone: () {},
38+
);
39+
});
40+
return server;
41+
}
42+
43+
void main() {
44+
const testPingInterval = Duration(milliseconds: 150);
45+
46+
setUp(() {
47+
RelaySocket.debugPingInterval = testPingInterval;
48+
});
49+
50+
tearDown(() {
51+
RelaySocket.debugPingInterval = RelaySocket.pingInterval;
52+
});
53+
54+
test('detects a peer that stops answering pings', () async {
55+
final server = await _silentAfterHandshakeServer();
56+
57+
final disconnected = Completer<Object?>();
58+
final socket = RelaySocket(
59+
wsUrl: 'ws://127.0.0.1:${server.port}',
60+
nsec: null,
61+
onMessage: (_) {},
62+
onConnected: () {},
63+
onDisconnected: (error) {
64+
if (!disconnected.isCompleted) disconnected.complete(error);
65+
},
66+
);
67+
unawaited(socket.connect());
68+
69+
var detected = true;
70+
try {
71+
await disconnected.future.timeout(testPingInterval * 4);
72+
} on TimeoutException {
73+
detected = false;
74+
}
75+
76+
expect(
77+
detected,
78+
isTrue,
79+
reason:
80+
'RelaySocket must surface an unanswered ping through onDisconnected',
81+
);
82+
83+
socket.dispose();
84+
await server.close();
85+
});
86+
87+
test('keeps an idle but healthy peer connected', () async {
88+
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
89+
server.transform(WebSocketTransformer()).listen((ws) {
90+
// A healthy relay answers pings without sending application data.
91+
ws.listen((_) {}, onError: (_) {}, onDone: () {});
92+
});
93+
94+
var tornDown = false;
95+
final socket = RelaySocket(
96+
wsUrl: 'ws://127.0.0.1:${server.port}',
97+
nsec: null,
98+
onMessage: (_) {},
99+
onConnected: () {},
100+
onDisconnected: (_) => tornDown = true,
101+
);
102+
unawaited(socket.connect());
103+
104+
await Future<void>.delayed(testPingInterval * 4);
105+
106+
expect(tornDown, isFalse);
107+
108+
await socket.disconnect();
109+
await server.close(force: true);
110+
});
111+
}

0 commit comments

Comments
 (0)