Skip to content

Commit 662014d

Browse files
authored
fix(mobile): stale community selection during mobile invite setup (#7951)
Buzz sets up starter channels when a person accepts an invite. If the phone already had a saved community, the first attempt could fail. Retry could then succeed. A delayed read could replace the new active community with the old one. The read now leaves the saved selection unchanged. The fix also delays channel-status updates until the channel provider finishes initialization. ### Before and after Controlled Flutter app captures against local relays, with the same delayed storage read. The before capture restores the pre-fix active-community provider in the test harness. The after capture uses the fixed provider. These are separate from the native iOS validation below. | Before: first attempt fails | After: first attempt succeeds | | --- | --- | | ![Before: starter channel setup error with Retry setup button](https://github.com/user-attachments/assets/14d8ba45-6e53-40ae-bc10-f219f08d2f92) | ![After: joined community with Continue to welcome channel button](https://github.com/user-attachments/assets/7dc32d9d-3aae-4378-913c-8ac68cc7d930) | ### Validation - Regression tests reproduce the delayed-read ordering and passing timing control; removing the channel sequencing safeguards makes their regressions fail. - Production app against local relays passes the forced race on the first attempt. - Native iOS simulator with an existing saved community accepted the original invite using a fresh identity, joined on the first attempt, and opened the welcome channel without Retry. Signed-off-by: Tom Brow <[email protected]>
1 parent f1e50be commit 662014d

6 files changed

Lines changed: 226 additions & 76 deletions

File tree

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

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ class _ChannelRefreshFence {
132132

133133
/// Whether the refresh still owns the active scope and generation.
134134
bool get isCurrent =>
135+
_coordinator.isMounted() &&
135136
_generation == _coordinator.generation &&
136137
scope == _coordinator.currentScope();
137138

@@ -303,6 +304,9 @@ Map<String, int> _memberCountsByChannelId(Iterable<NostrEvent> memberEvents) {
303304
/// Lives in this part file because `channels_provider.dart` sits against the
304305
/// repository-wide 1200-line file ceiling enforced by `just file-size-check`.
305306
class _ChannelRefreshCoordinator {
307+
/// Whether the owning provider can still read its current scope.
308+
final bool Function() isMounted;
309+
306310
/// Resolves the relay-and-identity scope that is active right now.
307311
final String Function() currentScope;
308312

@@ -315,16 +319,18 @@ class _ChannelRefreshCoordinator {
315319
int get generation => _generation;
316320

317321
_ChannelRefreshCoordinator({
322+
required this.isMounted,
318323
required this.currentScope,
319324
required this.loadStatus,
320325
});
321326

322327
/// Binds the fence to a notifier's [Ref] so the provider needs one line.
323328
///
324-
/// Both closures read rather than watch: the fence asks what the scope is
325-
/// right now, and must not make the notifier depend on it.
329+
/// The closures read rather than watch: the fence checks the current
330+
/// lifecycle and scope without making the notifier depend on them.
326331
factory _ChannelRefreshCoordinator.forRef(Ref ref) =>
327332
_ChannelRefreshCoordinator(
333+
isMounted: () => ref.mounted,
328334
currentScope: () => channelDirectoryScope(
329335
ref.read(relayConfigProvider).baseUrl,
330336
ref.read(myPubkeyProvider),
@@ -343,9 +349,16 @@ class _ChannelRefreshCoordinator {
343349
/// Used by callers that must carry the scope across later awaits even when
344350
/// they do not refresh discovery, so a membership-only refresh cannot install
345351
/// an old scope's list either.
346-
_ChannelRefreshFence beginRefresh({required bool fetchesDirectory}) {
352+
Future<_ChannelRefreshFence> beginRefresh({
353+
required bool fetchesDirectory,
354+
}) async {
347355
final scope = currentScope();
348356
final generation = ++_generation;
357+
final fence = _ChannelRefreshFence(this, scope, generation);
358+
// Acquire ownership synchronously, but let the provider finish building
359+
// before changing another provider's directory status.
360+
await Future<void>.value();
361+
fence.ensureCurrent();
349362
if (!fetchesDirectory) {
350363
final status = loadStatus();
351364
if (status.isLoading(scope)) {
@@ -359,7 +372,7 @@ class _ChannelRefreshCoordinator {
359372
status.markError(scope);
360373
}
361374
}
362-
return _ChannelRefreshFence(this, scope, generation);
375+
return fence;
363376
}
364377

365378
/// Fetches the directory under [fence], or throws if the fence is retired.

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
187187
// Acquire request ownership before the first relay await. Every channel-list
188188
// path uses this fence so completion order cannot let an older ordinary,
189189
// directory, or reconnect refresh replace a newer membership list.
190-
final fence = _refreshCoordinator.beginRefresh(
190+
final fence = await _refreshCoordinator.beginRefresh(
191191
fetchesDirectory: fetchDirectory,
192192
);
193193

‎mobile/lib/shared/community/community_provider.dart‎

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -618,21 +618,11 @@ final activeCommunityProvider = FutureProvider<Community?>((ref) async {
618618

619619
if (communities.isEmpty) return null;
620620

621-
if (activeId == null) {
622-
// No active ID stored but communities exist — fall back to first.
623-
await storage.saveActiveId(communities.first.id);
624-
return communities.first;
625-
}
626-
627-
try {
628-
return communities.firstWhere((w) => w.id == activeId);
629-
} on StateError {
630-
// Active ID points to a community that no longer exists.
631-
// Fall back to first community.
632-
if (communities.isNotEmpty) {
633-
await storage.saveActiveId(communities.first.id);
634-
return communities.first;
635-
}
636-
return null;
637-
}
621+
// This projection can outlive the list it captured above. Never persist a
622+
// fallback here: a newer authentication may already have selected a community
623+
// absent from that list. Authentication owns durable active-ID repair.
624+
return communities.firstWhere(
625+
(community) => community.id == activeId,
626+
orElse: () => communities.first,
627+
);
638628
});

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

Lines changed: 75 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -293,67 +293,88 @@ void main() {
293293
);
294294
});
295295

296-
test(
297-
'ordinary refresh settles a superseded directory load for retry',
298-
() async {
299-
final session = _FakeRelaySession(
300-
memberships: [_membership(_channelA, myPk)],
301-
metadata: [
302-
_meta(id: _channelA, name: 'general'),
303-
_meta(id: _channelB, name: 'discoverable'),
304-
],
305-
);
306-
final container = _buildContainer(session: session);
307-
addTearDown(container.dispose);
296+
for (final rebuild in [false, true]) {
297+
test(
298+
'${rebuild ? 'Same-scope rebuild' : 'Ordinary refresh'} settles a superseded directory load for retry',
299+
() async {
300+
final session = _FakeRelaySession(
301+
memberships: [_membership(_channelA, myPk)],
302+
metadata: [
303+
_meta(id: _channelA, name: 'general'),
304+
_meta(id: _channelB, name: 'discoverable'),
305+
],
306+
);
307+
final container = _buildContainer(session: session);
308+
addTearDown(container.dispose);
308309

309-
expect(
310-
(await container.read(
311-
channelsProvider.future,
312-
)).map((channel) => channel.id),
313-
[_channelA],
314-
);
310+
expect(
311+
(await container.read(
312+
channelsProvider.future,
313+
)).map((channel) => channel.id),
314+
[_channelA],
315+
);
315316

316-
session.pauseNextDirectoryQuery();
317-
final directory = container
318-
.read(channelsProvider.notifier)
319-
.retryDirectory();
320-
await session.nextDirectoryQueryStarted;
317+
session.pauseNextDirectoryQuery();
318+
final directory = container
319+
.read(channelsProvider.notifier)
320+
.retryDirectory();
321+
await session.nextDirectoryQueryStarted;
322+
323+
if (rebuild) {
324+
// A same-scope configuration rebuild can overlap an in-flight
325+
// directory request when onboarding settles its community providers.
326+
final config = container.read(relayConfigProvider);
327+
container
328+
.read(relayConfigProvider.notifier)
329+
.update(baseUrl: config.baseUrl, nsec: config.nsec);
330+
await container.read(channelsProvider.future);
331+
} else {
332+
await container.read(channelsProvider.notifier).refresh();
333+
}
321334

322-
// A foreground, reconnect, pull-to-refresh, or membership update can
323-
// start an ordinary refresh while Browse is still loading discovery.
324-
await container.read(channelsProvider.notifier).refresh();
335+
session.resumePausedDirectoryQuery();
336+
await directory;
337+
await _settle();
325338

326-
session.resumePausedDirectoryQuery();
327-
await directory;
328-
await _settle();
339+
expect(
340+
container.read(channelDirectoryLoadStatusProvider).status,
341+
ChannelDirectoryLoadStatus.error,
342+
);
343+
expect(
344+
container
345+
.read(channelsProvider)
346+
.requireValue
347+
.map((channel) => channel.id),
348+
[_channelA],
349+
);
329350

330-
expect(
331-
container.read(channelDirectoryLoadStatusProvider).status,
332-
ChannelDirectoryLoadStatus.error,
333-
);
334-
expect(
335-
container
336-
.read(channelsProvider)
337-
.requireValue
338-
.map((channel) => channel.id),
339-
[_channelA],
340-
);
351+
await container.read(channelsProvider.notifier).retryDirectory();
341352

342-
await container.read(channelsProvider.notifier).retryDirectory();
353+
expect(
354+
container.read(channelDirectoryLoadStatusProvider).status,
355+
ChannelDirectoryLoadStatus.loaded,
356+
);
357+
expect(
358+
container
359+
.read(channelsProvider)
360+
.requireValue
361+
.map((channel) => channel.id),
362+
unorderedEquals([_channelA, _channelB]),
363+
);
364+
},
365+
);
366+
}
343367

344-
expect(
345-
container.read(channelDirectoryLoadStatusProvider).status,
346-
ChannelDirectoryLoadStatus.loaded,
347-
);
348-
expect(
349-
container
350-
.read(channelsProvider)
351-
.requireValue
352-
.map((channel) => channel.id),
353-
unorderedEquals([_channelA, _channelB]),
354-
);
355-
},
356-
);
368+
test('refresh disposed before directory settlement writes nothing', () async {
369+
final session = _FakeRelaySession(memberships: const []);
370+
final container = _buildContainer(session: session);
371+
await container.read(channelsProvider.future);
372+
373+
final refresh = container.read(channelsProvider.notifier).refresh();
374+
container.dispose();
375+
376+
await expectLater(refresh, completes);
377+
});
357378

358379
test(
359380
'community switch discards a stale directory success from the old relay',
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import 'dart:async';
2+
3+
import 'package:buzz/features/invites/invite_join_provider.dart';
4+
import 'package:buzz/shared/auth/auth.dart';
5+
import 'package:buzz/shared/deeplink/deep_link.dart';
6+
import 'package:flutter_test/flutter_test.dart';
7+
import 'package:hooks_riverpod/hooks_riverpod.dart';
8+
import 'package:http/http.dart' as http;
9+
import 'package:http/testing.dart';
10+
import 'package:nostr/nostr.dart' as nostr;
11+
12+
import '../../shared/community/community_storage_test.dart';
13+
14+
void main() {
15+
for (final finishReadBeforeJoin in [false, true]) {
16+
test('first invite setup succeeds when old active read finishes '
17+
'${finishReadBeforeJoin ? 'before' : 'after'} new selection', () async {
18+
final storage = _PausedActiveReadStorage();
19+
final old = Community.create(
20+
name: 'Existing',
21+
relayUrl: 'wss://old.example.com',
22+
nsec: nostr.Keys.generate().nsec,
23+
);
24+
await storage.save(old);
25+
await storage.saveActiveId(old.id);
26+
var recoveryCalls = 0;
27+
final container = ProviderContainer(
28+
overrides: [
29+
communityStorageProvider.overrideWithValue(storage),
30+
communitySnapshotWriterProvider.overrideWithValue((_) async {}),
31+
inviteJoinHttpClientProvider.overrideWithValue(
32+
MockClient(
33+
(_) async => http.Response(
34+
'{"status":"joined","host":"new.example.com","role":"member"}',
35+
200,
36+
),
37+
),
38+
),
39+
inviteJoinRecoveryProvider.overrideWithValue((_) {
40+
recoveryCalls++;
41+
return _SuccessfulRecovery();
42+
}),
43+
],
44+
);
45+
addTearDown(container.dispose);
46+
// The app restores authentication before displaying the invite.
47+
await container.read(authProvider.future);
48+
storage.pauseNextRead = true;
49+
final oldProjection = container.read(activeCommunityProvider.future);
50+
await storage.readStarted.future;
51+
if (finishReadBeforeJoin) {
52+
storage.resumeRead.complete();
53+
await oldProjection;
54+
}
55+
final join = container.read(inviteJoinProvider.notifier);
56+
await join.prepare(
57+
const InviteDeepLink(
58+
relayUrl: 'wss://new.example.com',
59+
code: 'test-invite',
60+
),
61+
);
62+
await join.confirmJoin();
63+
await oldProjection;
64+
65+
final result = container.read(inviteJoinProvider);
66+
expect(result.status, InviteJoinStatus.success);
67+
expect(result.errorMessage, isNull);
68+
expect(recoveryCalls, 1);
69+
final communities = await storage.loadAll();
70+
final joined = communities.singleWhere((c) => c.id != old.id);
71+
expect(await storage.loadActiveId(), joined.id);
72+
expect(joined.starterSetupIncomplete, isFalse);
73+
expect(
74+
(await container.read(activeCommunityProvider.future))?.id,
75+
joined.id,
76+
);
77+
});
78+
}
79+
}
80+
81+
class _SuccessfulRecovery implements InviteJoinRecovery {
82+
@override
83+
Future<String?> ensureStarterChannels() async => 'welcome';
84+
}
85+
86+
/// Delays the storage read after the provider captures its community list.
87+
/// All reads and writes succeed; only their ordering changes.
88+
class _PausedActiveReadStorage extends CommunityStorage {
89+
_PausedActiveReadStorage() : super(secure: FakeSecureStorage());
90+
91+
bool pauseNextRead = false;
92+
final readStarted = Completer<void>();
93+
final resumeRead = Completer<void>();
94+
95+
@override
96+
Future<String?> loadActiveId() async {
97+
if (pauseNextRead) {
98+
pauseNextRead = false;
99+
readStarted.complete();
100+
await resumeRead.future;
101+
}
102+
return super.loadActiveId();
103+
}
104+
105+
@override
106+
Future<void> saveActiveId(String id) async {
107+
await super.saveActiveId(id);
108+
if (readStarted.isCompleted && !resumeRead.isCompleted) {
109+
resumeRead.complete();
110+
}
111+
}
112+
}

‎mobile/test/shared/community/community_provider_test.dart‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,19 @@ void main() {
686686
expect(active.name, 'Test');
687687
});
688688

689+
test('falls back without persisting when active ID is missing', () async {
690+
final community = Community.create(
691+
name: 'Fallback',
692+
relayUrl: 'https://test.example.com',
693+
);
694+
await communityStorage.save(community);
695+
container = createContainer();
696+
697+
final active = await container.read(activeCommunityProvider.future);
698+
expect(active?.id, community.id);
699+
expect(await communityStorage.loadActiveId(), isNull);
700+
});
701+
689702
test('falls back to first community if active ID is invalid', () async {
690703
container = createContainer();
691704
await container.read(communityListProvider.future);
@@ -705,6 +718,7 @@ void main() {
705718
final active = await container.read(activeCommunityProvider.future);
706719
expect(active, isNotNull);
707720
expect(active!.id, ws.id);
721+
expect(await communityStorage.loadActiveId(), 'nonexistent-id');
708722
});
709723
});
710724
}

0 commit comments

Comments
 (0)