From 7b8066fb94b927d0e4fdbad6d29e51e70fbacdb2 Mon Sep 17 00:00:00 2001 From: Wes Date: Mon, 16 Nov 2026 12:12:09 -0700 Subject: [PATCH] fix(mobile): keep the relay session across auth reloads (#9543) ## Summary `RelaySessionNotifier.build()` watched the whole `authProvider` but only read the signed-in status. Every `ref.invalidate(authProvider)` therefore rebuilt the session: the socket and all live subscriptions were dropped, and every screen resubscribed and republished presence and read state at once. An invite join invalidates auth twice for the same identity (3 sockets in about half a second), and each community switch does it again, producing a REQ burst the relay answers with `CLOSED rate-limited`. The session now watches only `(status, community.pubkey)` via `select`, so it still rebuilds when the user signs in or out, or switches identity while signed in. Relay URL and signing key changes continue to rebuild through `relayConfigProvider`, which is unchanged. ### Related issue None found. ### Testing - New regression test in `relay_session_test.dart`: with a connected socket and a live subscription, two auth invalidations for the same identity keep 1 socket, 0 disposes, `connected` status and a working subscription; a pubkey change then rebuilds to a second socket, and signing out disposes it. - The test fails on `main` without the fix (`Expected: an object with length of <1>`) and passes with it. - `just mobile-install mobile-check mobile-test`: format clean, `flutter analyze` no issues, 4909 tests passed (71 skipped), plus the native-secp256k1 package suite (27 passed). ### Before and after: first-launch invite join (simulator) Captured on a freshly erased iPhone 17 simulator with a one-use invite for each run, counting relay traffic for this identity in the first 5 s after launch. Before is `main` at `1a5c6939c`; after is this branch at `8beda6aea`. | | Before | After | |---|---|---| | Relay sockets opened during the join | 3 | **1** | | Relay frames in the first 5 s | 72 | 57 | | `OK false` for kinds 20001/30078 | 2 | **0** | | REQs refused with `quota_exceeded` | 16 | 6 | | Message posted after the join arrives live | yes | yes, on the same socket | The session rebuild is fixed: the join keeps one socket and its subscriptions. The original target of fewer than 50 frames in 5 s is not met. The remaining burst is about 31 separate single-document kind 30078 reads (`limit:1`, `authors` = self) at about +1.1 s, and all 6 remaining `quota_exceeded` refusals are among them. Those reads don't come from session rebuilds, so they'll be handled in a separate change rather than in this PR. - Not yet done: a run on a physical device of the first-launch join flow. Signed-off-by: Wes Co-authored-by: Mantis <530af7635ef7d0e1a5189d234338db88cb4ef1ede7119b4ebb4fb05c3eafe3b1@buzz.block.builderlab.xyz> --- mobile/lib/shared/relay/relay_session.dart | 4 +- .../lib/shared/relay/relay_session_auth.dart | 7 ++ .../test/shared/relay/relay_session_test.dart | 104 ++++++++++++++++++ 3 files changed, 113 insertions(+), 2 deletions(-) diff --git a/mobile/lib/shared/relay/relay_session.dart b/mobile/lib/shared/relay/relay_session.dart index cf4260df54..ef2d7beec7 100644 --- a/mobile/lib/shared/relay/relay_session.dart +++ b/mobile/lib/shared/relay/relay_session.dart @@ -125,7 +125,7 @@ class RelaySessionNotifier extends Notifier { SessionState build() { final config = ref.watch(relayConfigProvider); _relayUrl = config.baseUrl; - final authState = ref.watch(authProvider); + final auth = ref.watch(authProvider.select(_sessionAuthKey)); _ageRestricted = ref.watch(ageSignalProvider) == AgeSignalState.restricted; // Reset disposed flag — build() may re-run on the same Notifier instance @@ -135,7 +135,7 @@ class RelaySessionNotifier extends Notifier { ref.onDispose(_dispose); // Auto-connect when authenticated and we have a signing key (NIP-42 AUTH). - final isAuthenticated = authState.value?.status == AuthStatus.authenticated; + final isAuthenticated = auth.status == AuthStatus.authenticated; if (!_ageRestricted && isAuthenticated && config.nsec != null) { // Schedule connection after build completes. Future.microtask(() => _connect(config)); diff --git a/mobile/lib/shared/relay/relay_session_auth.dart b/mobile/lib/shared/relay/relay_session_auth.dart index 7c60cc37f1..f958d75006 100644 --- a/mobile/lib/shared/relay/relay_session_auth.dart +++ b/mobile/lib/shared/relay/relay_session_auth.dart @@ -1,5 +1,12 @@ part of 'relay_session.dart'; +/// The auth fields the session depends on: sign-in status and identity. +/// Watching only these keeps an auth reload, such as an invalidation that +/// re-reads the same community, from dropping the socket and subscriptions. +({AuthStatus? status, String? pubkey}) _sessionAuthKey( + AsyncValue auth, +) => (status: auth.value?.status, pubkey: auth.value?.community?.pubkey); + /// Pass the signer's hex [pubkey] when it is already known: deriving it from /// the key costs about a third of a signature, on the UI isolate. String buildNip98AuthHeader({ diff --git a/mobile/test/shared/relay/relay_session_test.dart b/mobile/test/shared/relay/relay_session_test.dart index f065bb7dd3..6d50b90fbe 100644 --- a/mobile/test/shared/relay/relay_session_test.dart +++ b/mobile/test/shared/relay/relay_session_test.dart @@ -12,6 +12,7 @@ import 'package:buzz/features/age_gate/age_signal_provider.dart'; import 'package:buzz/features/channels/agent_activity/observer_subscription.dart'; import 'package:buzz/features/channels/agent_activity/observer_models.dart'; import 'package:buzz/shared/auth/auth_provider.dart'; +import 'package:buzz/shared/community/community.dart'; import 'package:buzz/shared/relay/relay.dart'; import 'package:buzz/shared/relay/relay_query_response.dart'; @@ -1078,6 +1079,92 @@ void main() { expect(session.state.status, SessionStatus.connected); }); + test( + 'auth reloads keep the socket until status or identity changes', + () async { + final sockets = <_ControlledRelaySocket>[]; + final keychain = nostr.Keys.generate(); + final auth = _ReloadingAuthNotifier()..pubkey = keychain.public; + final session = RelaySessionNotifier( + socketFactory: + ({ + required wsUrl, + required nsec, + required onMessage, + required onConnected, + required onDisconnected, + }) { + final socket = _ControlledRelaySocket( + wsUrl: wsUrl, + nsec: nsec, + onMessage: onMessage, + onConnected: onConnected, + onDisconnected: onDisconnected, + ); + sockets.add(socket); + return socket; + }, + ); + final container = ProviderContainer( + overrides: [ + relaySessionProvider.overrideWith(() => session), + relayConfigProvider.overrideWith( + () => _FakeRelayConfigNotifier( + baseUrl: 'https://relay.example', + nsec: keychain.nsec, + ), + ), + authProvider.overrideWith(() => auth), + ], + ); + addTearDown(container.dispose); + await container.read(authProvider.future); + final listener = container.listen(relaySessionProvider, (_, _) {}); + addTearDown(listener.close); + await Future.delayed(Duration.zero); + sockets.single.connectSuccessfully(); + + final events = []; + final subscribed = session.subscribe(_channelFilter, events.add); + await Future.delayed(Duration.zero); + final subId = sockets.single.sent.single[1]; + session.debugHandleSocketMessageForTest(['EOSE', subId]); + await subscribed; + + // An invite join reloads auth twice for the same signed-in identity. + for (var i = 0; i < 2; i++) { + container.invalidate(authProvider); + await container.read(authProvider.future); + await Future.delayed(Duration.zero); + } + + expect(sockets, hasLength(1)); + expect(sockets.single.disposeCalls, 0); + expect(session.state.status, SessionStatus.connected); + session.debugHandleSocketMessageForTest([ + 'EVENT', + subId, + _event().toJson(), + ]); + session.debugFlushEventBuffer(); + expect(events.map((event) => event.id), ['event-1']); + + auth.pubkey = nostr.Keys.generate().public; + container.invalidate(authProvider); + await container.read(authProvider.future); + await Future.delayed(Duration.zero); + expect(sockets, hasLength(2)); + expect(sockets.first.disposeCalls, 1); + + auth.status = AuthStatus.unauthenticated; + container.invalidate(authProvider); + await container.read(authProvider.future); + await Future.delayed(Duration.zero); + expect(sockets, hasLength(2)); + expect(sockets.last.disposeCalls, 1); + }, + ); + test('does not schedule reconnects after background disconnect', () { final session = RelaySessionNotifier(); final container = ProviderContainer( @@ -2267,6 +2354,23 @@ class _AuthenticatedAuthNotifier extends AuthNotifier { const AuthState(status: AuthStatus.authenticated); } +class _ReloadingAuthNotifier extends AuthNotifier { + AuthStatus status = AuthStatus.authenticated; + String? pubkey; + + @override + Future build() async => AuthState( + status: status, + community: Community( + id: 'community-1', + name: 'Example', + relayUrl: 'https://relay.example', + pubkey: pubkey, + addedAt: DateTime(2026), + ), + ); +} + class _ControlledRelaySocket extends RelaySocket { final void Function() _connected; final void Function(Object? error) _disconnected;