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;