Skip to content

Commit c73b028

Browse files
loganjLarryclaude
committed
fix(mobile): keep search's directory loads from losing channels
Two races found by the Codex security review of this branch: - A community switch drops the cached directory, but the directory status still said the earlier community was loaded. Switching away and back within the search TTL skipped the reload, so search lost unjoined channels with no notice. ensureDirectoryLoaded now also requires the cached directory to come from the current scope. - A search during the first channel load started a directory refresh that retired the pending build. If the build's reply arrived last, its stale failure replaced the installed list. retryDirectory now waits for a pending first load, as fetchFresh does. Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Logan Johnson <[email protected]>
1 parent fe42765 commit c73b028

2 files changed

Lines changed: 97 additions & 2 deletions

File tree

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

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,9 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
7676
String? _memberSnapshotPubkey;
7777
Map<String, List<ChannelMember>> _memberSnapshotsByChannelId = const {};
7878
List<NostrEvent> _directoryMetas = const [];
79+
// The scope [_directoryMetas] came from. A community switch drops them, so
80+
// the directory status alone cannot say this scope's directory is cached.
81+
String? _directoryMetasScope;
7982
Set<String> _hiddenDmIds = const {};
8083

8184
/// Fences directory responses to the relay and identity that requested them.
@@ -173,6 +176,7 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
173176
_memberSnapshotPubkey = pubkey;
174177
_memberSnapshotsByChannelId = const {};
175178
_directoryMetas = const [];
179+
_directoryMetasScope = null;
176180
_hiddenDmIds = const {};
177181
// Retire any in-flight directory request: its response describes the
178182
// previous relay or identity and must not reach this scope's state.
@@ -340,7 +344,10 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
340344
// ever regresses. The composite cursor preserves tied-timestamp rows.
341345
if (fetchDirectory) {
342346
final metas = await _refreshCoordinator.loadDirectory(session, fence);
343-
if (metas != null) _directoryMetas = metas;
347+
if (metas != null) {
348+
_directoryMetas = metas;
349+
_directoryMetasScope = fence.scope;
350+
}
344351
}
345352

346353
// Merge and dedupe by `d` tag. Kind:39000 is parameterized-replaceable,
@@ -1073,6 +1080,7 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
10731080
final loadedAt = directoryState.loadedAt;
10741081
final fresh =
10751082
directoryState.status == ChannelDirectoryLoadStatus.loaded &&
1083+
_directoryMetasScope == scope &&
10761084
(maxAge == null ||
10771085
(loadedAt != null && DateTime.now().difference(loadedAt) < maxAge));
10781086
if (directoryState.scope == scope &&
@@ -1085,7 +1093,6 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
10851093

10861094
/// Retries channel discovery while retaining the current channel list.
10871095
Future<void> retryDirectory() async {
1088-
final previousChannels = state.value;
10891096
final directoryStatus = ref.read(
10901097
channelDirectoryLoadStatusProvider.notifier,
10911098
);
@@ -1102,6 +1109,16 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
11021109
directoryStatus.markError(scope);
11031110
return;
11041111
}
1112+
// Let a pending first load finish, as fetchFresh does. This request
1113+
// would retire it, and its late failure would replace the list.
1114+
final generation = _buildGeneration;
1115+
try {
1116+
await future;
1117+
} catch (_) {
1118+
// A failed first load must not prevent the directory request.
1119+
}
1120+
if (!ref.mounted || generation != _buildGeneration) return;
1121+
final previousChannels = state.value;
11051122
try {
11061123
state = AsyncData(
11071124
await _fetch(subscribeLive: true, fetchDirectory: true),

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

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,84 @@ void main() {
8383
expect(session.directoryQueryFilters, hasLength(reads * 2));
8484
});
8585

86+
test(
87+
'ensureDirectoryLoaded reads again after the community switches away and back',
88+
() async {
89+
final session = _FakeRelaySession(
90+
memberships: const [],
91+
metadata: [_meta(id: _channelA, name: 'general')],
92+
);
93+
final container = _buildContainer(session: session);
94+
addTearDown(container.dispose);
95+
await container.read(channelsProvider.future);
96+
final config = container.read(relayConfigProvider.notifier);
97+
final communityA = container.read(relayConfigProvider).baseUrl;
98+
const maxAge = Duration(hours: 1);
99+
100+
await container
101+
.read(channelsProvider.notifier)
102+
.ensureDirectoryLoaded(maxAge: maxAge);
103+
expect(container.read(channelsProvider).requireValue.map((c) => c.id), [
104+
_channelA,
105+
]);
106+
107+
// Switch to B without loading its directory, then back to A. The switch
108+
// drops A's cached directory, so A's earlier load no longer serves it.
109+
config.update(baseUrl: 'https://community-b.example');
110+
await container.read(channelsProvider.future);
111+
config.update(baseUrl: communityA);
112+
await container.read(channelsProvider.future);
113+
final reads = session.directoryQueryFilters.length;
114+
115+
await container
116+
.read(channelsProvider.notifier)
117+
.ensureDirectoryLoaded(maxAge: maxAge);
118+
expect(session.directoryQueryFilters.length, greaterThan(reads));
119+
expect(container.read(channelsProvider).requireValue.map((c) => c.id), [
120+
_channelA,
121+
]);
122+
},
123+
);
124+
125+
test('a directory load during the first channel load waits for it', () async {
126+
final session = _FakeRelaySession(
127+
memberships: [_membership(_channelA, myPk)],
128+
metadata: [
129+
_meta(id: _channelA, name: 'general'),
130+
_meta(id: _channelB, name: 'discoverable'),
131+
],
132+
);
133+
final container = _buildContainer(session: session);
134+
addTearDown(container.dispose);
135+
final sub = container.listen(channelsProvider, (_, _) {});
136+
addTearDown(sub.close);
137+
138+
// Search starts while the first load's member metadata is held.
139+
session.pauseNextMemberMetadataQuery();
140+
container.read(channelsProvider);
141+
await session.nextMemberMetadataQueryStarted;
142+
final directory = container
143+
.read(channelsProvider.notifier)
144+
.ensureDirectoryLoaded(maxAge: const Duration(seconds: 30));
145+
await _settle();
146+
147+
// The first load's reply arrives last. It must not replace the list.
148+
session.resumePausedMemberMetadataQuery();
149+
await directory;
150+
await _settle();
151+
152+
final state = container.read(channelsProvider);
153+
expect(state.hasError, isFalse);
154+
expect(
155+
state.requireValue.map((c) => c.id),
156+
unorderedEquals([_channelA, _channelB]),
157+
);
158+
expect(
159+
container.read(channelDirectoryLoadStatusProvider).status,
160+
ChannelDirectoryLoadStatus.loaded,
161+
);
162+
});
163+
86164
test('paginates channel discovery with a composite cursor', () async {
87165
final firstPage = List.generate(
88166
500,

0 commit comments

Comments
 (0)