refactor(mobile): remove unused CommunityListNotifier.addCommunity (#9896)

## Summary

`CommunityListNotifier.addCommunity` has no callers in the app.
Communities are saved through the auth flow
(`authenticateWithCommunity`), so the method, including its same-relay
credential replacement branch, is dead code that tests kept alive.

This deletes the method and the test that covered it. Tests that used it
only for setup now seed `CommunityStorage` before building the provider
container, which is how the app loads communities at startup.

## Changes

- Delete `addCommunity` and its now-unused import.
- Delete the `addCommunity adds to list` test.
- Trim the two credential replacement tests to the startup sweep and
removal coverage they also held, and delete the storage helper only they
used. The trimmed tests still seed a retired signer's channel-directory
file at startup, and check that the saved-message scope is cleared while
the active community still holds a removed account.
- `community_entry_requirements_test` keeps only the authentication
path; the community addition variant tested the deleted method.

### Added lines

Ignoring whitespace the diff is +99/-282. The added lines are:

- `await communityStorage.save(...)` in place of each removed
`addCommunity(...)` setup call.
- `createContainer()` and the initial list read, moved below the seeded
communities so the notifier loads them.
- Reindentation in `community_entry_requirements_test` after removing
its outer loop.
- In the startup sweep and saved-message purge tests: a
channel-directory seed helper with its assertions, and a listener that
checks the saved-message scope during removal. These keep coverage of
the provider's per-signer directory sweep and the scope's
retained-identity guard, which the replacement assertions used to
provide.

## Validation

- Full mobile test suite, analyze, format and file-size checks pass.
- No user-visible change, so no screenshots; the deleted code had no
production caller.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
This commit is contained in:
Tom Brow
2026-11-23 10:59:39 -08:00
committed by GitHub
parent 4a440b5932
commit 18e4b37d97
4 changed files with 236 additions and 390 deletions

View File

@@ -15,7 +15,6 @@ import '../auth/auth_provider.dart';
import '../channels/channel_list_snapshot.dart';
import '../channels/saved_message_store.dart';
import '../diagnostics/diagnostic_reporter.dart';
import '../hosted/community_entry_requirements.dart';
import '../profile/profile_snapshot.dart';
import '../push/dev_push_lease.dart';
import '../push/push_bridge.dart';
@@ -287,57 +286,6 @@ class CommunityListNotifier extends AsyncNotifier<List<Community>> {
return communities;
}
/// Add a community. If one with the same relay URL already exists, update
/// its credentials instead. Returns the effective community ID.
Future<String> addCommunity(Community community) async {
final sync = ref.read(knownCommunitySyncProvider);
community = await sync?.prepareAddition(community) ?? community;
await CommunityEntryRequirements.verify(
community,
ref.read(builderlabAccountProvider),
);
final storage = ref.read(communityStorageProvider);
final current = state.value ?? [];
// If a community with the same relay URL exists, update its credentials
// instead of creating a duplicate entry.
final existingIndex = current.indexWhere(
(w) => w.relayUrl == community.relayUrl,
);
if (existingIndex >= 0) {
final existing = current[existingIndex];
final updated = existing.copyWith(
pubkey: community.pubkey,
nsec: community.nsec,
accountSyncOwner: community.accountSyncOwner,
accountSyncRevision: community.accountSyncRevision,
);
final identityChanged =
_channelSnapshotPubkey(existing)?.toLowerCase() !=
_channelSnapshotPubkey(updated)?.toLowerCase();
if (identityChanged) await _removeChannelListSnapshot(existing);
await storage.save(updated);
final updatedList = [...current];
updatedList[existingIndex] = updated;
state = AsyncData(updatedList);
// The new account has its own image cache; drop the previous one's in
// the background.
if (identityChanged) unawaited(_removeOrphanMediaCaches());
await _removeOrphanChannelListSnapshots(updatedList);
await syncCommunitySnapshot(ref, updatedList);
sync?.trigger();
return existing.id;
}
await storage.save(community);
final updatedList = [...current, community];
state = AsyncData(updatedList);
await _removeOrphanChannelListSnapshots(updatedList);
await syncCommunitySnapshot(ref, updatedList);
sync?.trigger();
return community.id;
}
/// Removes a saved identity without letting awaited cleanup change the account
/// that confirmed its remote edit. An explicit null confirmation is local-only.
Future<void> removeCommunity(

View File

@@ -334,7 +334,14 @@ void _filterFeedbackTests(
nsec: keys.nsec,
pubkey: keys.public,
);
final other = Community.create(
name: 'Other community',
relayUrl: 'https://other.example',
nsec: keys.nsec,
pubkey: keys.public,
);
await storage.save(community);
await storage.save(other);
await storage.saveActiveId(community.id);
final relay = _FilterJourneyRelay();
await tester.pumpWidget(
@@ -469,13 +476,6 @@ void _filterFeedbackTests(
// Switching community still abandons the sheet.
await tester.tap(find.byTooltip('Team options'));
await tester.pumpAndSettle();
final other = Community.create(
name: 'Other community',
relayUrl: 'https://other.example',
nsec: keys.nsec,
pubkey: keys.public,
);
await communities.addCommunity(other);
await communities.switchCommunity(other.id);
await tester.pumpAndSettle();
expect(find.text(reopen), findsOneWidget);

View File

@@ -13,62 +13,52 @@ import '../community/community_storage_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
for (final useAuth in [true, false]) {
for (final host in [
'team.communities.buzz.xyz',
'team.communities.public.builderlabstaging.xyz',
'team.communities.public.builderlabstaging.xyz.',
]) {
test(
'accountless entry follows domain policy through '
'${useAuth ? "authentication" : "community addition"}: $host',
() async {
FlutterSecureStorage.setMockInitialValues({});
final storage = CommunityStorage(secure: FakeSecureStorage());
final container = ProviderContainer(
overrides: [communityStorageProvider.overrideWithValue(storage)],
);
addTearDown(container.dispose);
await container.read(authProvider.future);
await container.read(communityListProvider.future);
var transitions = 0;
container.read(communityTransitionProvider).register(() async {
transitions++;
});
final keys = nostr.Keys.generate();
final community = Community.create(
name: 'Hosted',
relayUrl: 'wss://$host',
pubkey: keys.public,
nsec: keys.nsec,
);
final pending = useAuth
? container
.read(authProvider.notifier)
.authenticateWithCommunity(community)
: container
.read(communityListProvider.notifier)
.addCommunity(community);
if (!HostedEnvironment.requiresAuth(host)) {
await pending;
expect((await storage.loadAll()).single.nsec, keys.nsec);
expect(
await storage.loadActiveId(),
useAuth ? community.id : isNull,
);
expect(transitions, useAuth ? 1 : 0);
return;
}
await expectLater(pending, throwsA(isA<AccountFailure>()));
expect(await storage.loadAll(), isEmpty);
expect(await storage.loadActiveId(), isNull);
expect(transitions, 0);
expect(
container.read(authProvider).value!.status,
AuthStatus.unauthenticated,
);
},
);
}
for (final host in [
'team.communities.buzz.xyz',
'team.communities.public.builderlabstaging.xyz',
'team.communities.public.builderlabstaging.xyz.',
]) {
test(
'accountless entry follows domain policy through authentication: $host',
() async {
FlutterSecureStorage.setMockInitialValues({});
final storage = CommunityStorage(secure: FakeSecureStorage());
final container = ProviderContainer(
overrides: [communityStorageProvider.overrideWithValue(storage)],
);
addTearDown(container.dispose);
await container.read(authProvider.future);
await container.read(communityListProvider.future);
var transitions = 0;
container.read(communityTransitionProvider).register(() async {
transitions++;
});
final keys = nostr.Keys.generate();
final community = Community.create(
name: 'Hosted',
relayUrl: 'wss://$host',
pubkey: keys.public,
nsec: keys.nsec,
);
final pending = container
.read(authProvider.notifier)
.authenticateWithCommunity(community);
if (!HostedEnvironment.requiresAuth(host)) {
await pending;
expect((await storage.loadAll()).single.nsec, keys.nsec);
expect(await storage.loadActiveId(), community.id);
expect(transitions, 1);
return;
}
await expectLater(pending, throwsA(isA<AccountFailure>()));
expect(await storage.loadAll(), isEmpty);
expect(await storage.loadActiveId(), isNull);
expect(transitions, 0);
expect(
container.read(authProvider).value!.status,
AuthStatus.unauthenticated,
);
},
);
}
}

View File

@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'dart:convert';
import 'dart:io';
@@ -8,10 +9,10 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:hooks_riverpod/misc.dart';
import 'package:buzz/shared/channels/channel_list_snapshot.dart';
import 'package:buzz/shared/channels/open_channel_directory_storage.dart';
import 'package:buzz/shared/channels/saved_message_store.dart';
import 'package:buzz/shared/crypto/event_signing.dart';
import 'package:buzz/shared/relay/nostr_models.dart';
import 'package:buzz/shared/channels/open_channel_directory_storage.dart';
import 'package:buzz/shared/theme/theme_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
@@ -133,33 +134,16 @@ void main() {
expect(snapshots, hasLength(1));
});
test('addCommunity adds to list', () async {
container = createContainer();
await container.read(communityListProvider.future);
final ws = Community.create(
name: 'Test',
relayUrl: 'https://test.example.com',
);
await container.read(communityListProvider.notifier).addCommunity(ws);
final communities = await container.read(communityListProvider.future);
expect(communities, hasLength(1));
expect(communities.first.name, 'Test');
});
test(
'push notifications default on and opt-out survives restart',
() async {
container = createContainer();
await container.read(communityListProvider.future);
final community = Community.create(
name: 'Test',
relayUrl: 'https://test.example.com',
);
await container
.read(communityListProvider.notifier)
.addCommunity(community);
await communityStorage.save(community);
container = createContainer();
await container.read(communityListProvider.future);
expect(
(await container.read(
communityListProvider.future,
@@ -185,8 +169,6 @@ void main() {
test(
'lease retry reserves beyond a locally unaccepted generation',
() async {
container = createContainer();
await container.read(communityListProvider.future);
final subscription = BuzzPushSubscription(
filter: BuzzPushFilter(kinds: const [9], pTags: ['a' * 64]),
notificationClass: 'default',
@@ -202,8 +184,10 @@ void main() {
pushNotificationsEnabled: true,
pushSubscriptionState: subscriptionState,
);
await communityStorage.save(community);
container = createContainer();
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(community);
expect(await notifier.reservePushLeaseGeneration(community.id), 5);
expect(await notifier.reservePushLeaseGeneration(community.id), 6);
@@ -214,8 +198,6 @@ void main() {
);
test('older lease success cannot regress accepted generation', () async {
container = createContainer();
await container.read(communityListProvider.future);
final subscription = BuzzPushSubscription(
filter: BuzzPushFilter(kinds: const [9], pTags: ['a' * 64]),
notificationClass: 'default',
@@ -230,8 +212,10 @@ void main() {
desired: [subscription],
).withAccepted(subscriptions: [subscription], generation: 6),
);
await communityStorage.save(community);
container = createContainer();
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(community);
expect(
await notifier.markPushLeaseAccepted(
@@ -251,8 +235,6 @@ void main() {
});
test('lease success cannot accept stale desired subscriptions', () async {
container = createContainer();
await container.read(communityListProvider.future);
final original = BuzzPushSubscription(
filter: BuzzPushFilter(kinds: const [9], pTags: ['a' * 64]),
notificationClass: 'default',
@@ -271,8 +253,10 @@ void main() {
desired: [original],
),
);
await communityStorage.save(community);
container = createContainer();
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(community);
final generation = await notifier.reservePushLeaseGeneration(
community.id,
@@ -299,8 +283,6 @@ void main() {
});
test('opt-out tombstones an in-flight first publication', () async {
container = createContainer();
await container.read(communityListProvider.future);
final subscription = BuzzPushSubscription(
filter: BuzzPushFilter(kinds: const [9], pTags: ['a' * 64]),
notificationClass: 'default',
@@ -315,8 +297,10 @@ void main() {
desired: [subscription],
),
);
await communityStorage.save(community);
container = createContainer();
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(community);
expect(await notifier.reservePushLeaseGeneration(community.id), 1);
await notifier.setPushNotificationsEnabled(community.id, false);
@@ -335,8 +319,6 @@ void main() {
});
test('opt-out persists first and publishes a higher tombstone', () async {
container = createContainer();
await container.read(communityListProvider.future);
final subscription = BuzzPushSubscription(
filter: BuzzPushFilter(kinds: const [9], pTags: ['a' * 64]),
notificationClass: 'default',
@@ -351,8 +333,10 @@ void main() {
desired: [subscription],
).withAccepted(subscriptions: [subscription], generation: 7),
);
await communityStorage.save(community);
container = createContainer();
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(community);
await notifier.setPushNotificationsEnabled(community.id, false);
@@ -385,8 +369,6 @@ void main() {
throw StateError('injected tombstone failure');
}
};
container = createContainer();
await container.read(communityListProvider.future);
final subscription = BuzzPushSubscription(
filter: BuzzPushFilter(kinds: const [9], pTags: ['a' * 64]),
notificationClass: 'default',
@@ -401,9 +383,9 @@ void main() {
desired: [subscription],
).withAccepted(subscriptions: [subscription], generation: 7),
);
await container
.read(communityListProvider.notifier)
.addCommunity(community);
await communityStorage.save(community);
container = createContainer();
await container.read(communityListProvider.future);
await container
.read(communityListProvider.notifier)
@@ -516,6 +498,7 @@ void main() {
).withAccepted(subscriptions: [subscription], generation: 7),
);
// The real deactivator, unlike the injected one createContainer uses.
await communityStorage.save(community);
container = ProviderContainer(
overrides: [
communityStorageProvider.overrideWithValue(communityStorage),
@@ -532,7 +515,6 @@ void main() {
);
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(community);
await notifier.setPushNotificationsEnabled(community.id, false);
await notifier.retryPendingPushLeaseTombstone(community.id);
@@ -550,14 +532,13 @@ void main() {
);
test('removeCommunity removes from list', () async {
container = createContainer();
await container.read(communityListProvider.future);
final ws = Community.create(
name: 'Test',
relayUrl: 'https://test.example.com',
);
await container.read(communityListProvider.notifier).addCommunity(ws);
await communityStorage.save(ws);
container = createContainer();
await container.read(communityListProvider.future);
await container
.read(communityListProvider.notifier)
.removeCommunity(ws.id);
@@ -668,131 +649,113 @@ void main() {
]);
});
test('startup and credential replacement discard orphan snapshots and '
'image caches', () async {
final mediaRoot = await Directory.systemTemp.createTemp('media_root');
addTearDown(() => mediaRoot.delete(recursive: true));
Future<Directory> seedMedia(Directory directory) async {
await File('${directory.path}/image').create(recursive: true);
return directory;
}
Future<File> seedDirectory(String communityId, String signer) async {
final file = OpenChannelDirectoryStorage.fileFor(
mediaRoot,
communityId,
signer,
);
await file.create(recursive: true);
return file;
}
// Media sweeps run in the background.
Future<bool> eventuallyExists(FileSystemEntity directory) async {
for (var i = 0; i < 50 && await directory.exists(); i++) {
await Future<void>.delayed(const Duration(milliseconds: 10));
test(
'startup and removal discard orphan snapshots and image caches',
() async {
final mediaRoot = await Directory.systemTemp.createTemp('media_root');
addTearDown(() => mediaRoot.delete(recursive: true));
Future<Directory> seedMedia(Directory directory) async {
await File('${directory.path}/image').create(recursive: true);
return directory;
}
return directory.exists();
}
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
final cache = ChannelListSnapshotStorage(prefs);
const snapshot = ChannelListSnapshot(channels: [], hiddenDmIds: {});
final oldKeys = nostr.Keys.generate();
final newKeys = nostr.Keys.generate();
final midKeys = nostr.Keys.generate();
final community = Community.create(
name: 'Stored',
relayUrl: 'wss://cached.example.com:443',
nsec: oldKeys.nsec,
);
await communityStorage.save(community);
final oldToken = cache.capture(oldKeys.public, community.relayUrl);
final restoredToken = cache.capture('restored', 'https://orphan.example');
await cache.write(oldToken, snapshot);
await cache.write(restoredToken, snapshot);
await prefs.setString('unrelated', 'keep');
final oldMedia = await seedMedia(
MediaDiskCache.directoryFor(mediaRoot, community.id, oldKeys.public),
);
final orphanMedia = await seedMedia(
MediaDiskCache.communityDirectory(mediaRoot, 'restored'),
);
container = createContainer(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
mediaCacheRootProvider.overrideWith((ref) async => mediaRoot),
],
);
await container.read(communityListProvider.future);
expect(cache.read(oldKeys.public, community.relayUrl), isNotNull);
expect(cache.read('restored', 'https://orphan.example'), isNull);
expect(await cache.write(restoredToken, snapshot), isFalse);
expect(await eventuallyExists(orphanMedia), isFalse);
expect(await oldMedia.exists(), isTrue);
Future<File> seedDirectory(String communityId, String signer) async {
final file = OpenChannelDirectoryStorage.fileFor(
mediaRoot,
communityId,
signer,
);
await file.create(recursive: true);
return file;
}
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(community);
expect(cache.read(oldKeys.public, community.relayUrl), isNotNull);
expect(await cache.write(oldToken, snapshot), isTrue);
expect(await oldMedia.exists(), isTrue);
final midMedia = await seedMedia(
MediaDiskCache.directoryFor(mediaRoot, community.id, midKeys.public),
);
final newMedia = await seedMedia(
MediaDiskCache.directoryFor(mediaRoot, community.id, newKeys.public),
);
final oldDirectory = await seedDirectory(community.id, oldKeys.public);
final newDirectory = await seedDirectory(community.id, newKeys.public);
// Two quick replacements: the first one's sweep must not delete the
// newest account's cache.
await notifier.addCommunity(community.copyWith(nsec: midKeys.nsec));
await notifier.addCommunity(community.copyWith(nsec: newKeys.nsec));
expect(await eventuallyExists(midMedia), isFalse);
expect(cache.read(oldKeys.public, community.relayUrl), isNull);
expect(await cache.write(oldToken, snapshot), isFalse);
expect(await eventuallyExists(oldMedia), isFalse);
expect(await newMedia.exists(), isTrue);
expect(await eventuallyExists(oldDirectory), isFalse);
expect(await newDirectory.exists(), isTrue);
final newToken = cache.capture(newKeys.public, community.relayUrl);
await cache.write(newToken, snapshot);
await communityStorage.saveActiveId(community.id);
await notifier.removeCommunity(community.id);
expect(await communityStorage.loadAll(), isEmpty);
expect(prefs.getKeys(), {'unrelated'});
expect(await cache.write(newToken, snapshot), isFalse);
expect(await eventuallyExists(newMedia), isFalse);
expect(
await eventuallyExists(
MediaDiskCache.communityDirectory(mediaRoot, community.id),
),
isFalse,
);
// Media sweeps run in the background.
Future<bool> eventuallyExists(FileSystemEntity directory) async {
for (var i = 0; i < 50 && await directory.exists(); i++) {
await Future<void>.delayed(const Duration(milliseconds: 10));
}
return directory.exists();
}
// A backup restored without secure community records is swept at startup.
container.dispose();
await prefs.setString(
ChannelListSnapshotStorage.key('restored', 'https://orphan.example'),
'{"v":1,"channels":[],"hidden_dm_ids":[]}',
);
container = createContainer(
overrides: [savedPrefsProvider.overrideWithValue(prefs)],
);
await container.read(communityListProvider.future);
expect(prefs.getKeys(), {'unrelated'});
});
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
final cache = ChannelListSnapshotStorage(prefs);
const snapshot = ChannelListSnapshot(channels: [], hiddenDmIds: {});
final oldKeys = nostr.Keys.generate();
final community = Community.create(
name: 'Stored',
relayUrl: 'wss://cached.example.com:443',
nsec: oldKeys.nsec,
);
await communityStorage.save(community);
final oldToken = cache.capture(oldKeys.public, community.relayUrl);
final restoredToken = cache.capture(
'restored',
'https://orphan.example',
);
await cache.write(oldToken, snapshot);
await cache.write(restoredToken, snapshot);
await prefs.setString('unrelated', 'keep');
final oldMedia = await seedMedia(
MediaDiskCache.directoryFor(mediaRoot, community.id, oldKeys.public),
);
final orphanMedia = await seedMedia(
MediaDiskCache.communityDirectory(mediaRoot, 'restored'),
);
final oldDirectory = await seedDirectory(community.id, oldKeys.public);
final retiredDirectory = await seedDirectory(
community.id,
nostr.Keys.generate().public,
);
container = createContainer(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
mediaCacheRootProvider.overrideWith((ref) async => mediaRoot),
],
);
await container.read(communityListProvider.future);
expect(cache.read(oldKeys.public, community.relayUrl), isNotNull);
expect(cache.read('restored', 'https://orphan.example'), isNull);
expect(await cache.write(restoredToken, snapshot), isFalse);
expect(await eventuallyExists(orphanMedia), isFalse);
expect(await oldMedia.exists(), isTrue);
expect(await eventuallyExists(retiredDirectory), isFalse);
expect(await oldDirectory.exists(), isTrue);
test('startup, identity replacement and removal purge saved messages '
'from disk', () async {
await communityStorage.saveActiveId(community.id);
await container
.read(communityListProvider.notifier)
.removeCommunity(community.id);
expect(await communityStorage.loadAll(), isEmpty);
expect(prefs.getKeys(), {'unrelated'});
expect(await cache.write(oldToken, snapshot), isFalse);
expect(await eventuallyExists(oldMedia), isFalse);
expect(await eventuallyExists(oldDirectory), isFalse);
expect(
await eventuallyExists(
MediaDiskCache.communityDirectory(mediaRoot, community.id),
),
isFalse,
);
// A backup restored without secure community records is swept at startup.
container.dispose();
await prefs.setString(
ChannelListSnapshotStorage.key('restored', 'https://orphan.example'),
'{"v":1,"channels":[],"hidden_dm_ids":[]}',
);
container = createContainer(
overrides: [savedPrefsProvider.overrideWithValue(prefs)],
);
await container.read(communityListProvider.future);
expect(prefs.getKeys(), {'unrelated'});
},
);
test('startup and removal purge saved messages from disk', () async {
final root = await Directory.systemTemp.createTemp('saved_root');
addTearDown(() => root.delete(recursive: true));
final storage = _ObservedSaveStorage(fakeSecure);
communityStorage = storage;
final oldKeys = nostr.Keys.generate();
final midKeys = nostr.Keys.generate();
final newKeys = nostr.Keys.generate();
final community = Community.create(
name: 'Stored',
relayUrl: 'wss://cached.example.com:443',
@@ -800,8 +763,6 @@ void main() {
);
await communityStorage.save(community);
final oldSaved = (communityId: community.id, pubkey: oldKeys.public);
final midSaved = (communityId: community.id, pubkey: midKeys.public);
final newSaved = (communityId: community.id, pubkey: newKeys.public);
final orphanSaved = (communityId: 'restored', pubkey: oldKeys.public);
// A previous launch saved this account's messages and those of a
// community removed while the app was not running.
@@ -818,7 +779,7 @@ void main() {
// The active account is still published during revocation journaling.
removalInFlight = container
.read(savedMessageStoreProvider)
.capture(newSaved, _savedPage);
.capture(oldSaved, _savedPage);
return true;
},
);
@@ -828,53 +789,26 @@ void main() {
expect(await _readSaved(saved, orphanSaved), isNull);
expect(await _readSaved(saved, oldSaved), hasLength(1));
final notifier = container.read(communityListProvider.notifier);
await container.read(activeCommunityProvider.future);
expect(container.read(savedMessageScopeProvider), oldSaved);
final finishActiveRefresh = Completer<void>();
storage.activeReadGate = finishActiveRefresh.future;
addTearDown(() {
if (!finishActiveRefresh.isCompleted) finishActiveRefresh.complete();
});
// Re-adding the same account keeps its messages.
await notifier.addCommunity(community);
expect(container.read(activeCommunityProvider).isLoading, isTrue);
expect(container.read(savedMessageScopeProvider), oldSaved);
expect(await _readSaved(saved, oldSaved), hasLength(1));
// Retire refreshes from before cleanup and while the replacement is
// being persisted but the previous identity is still published.
final oldInFlight = saved.capture(oldSaved, _savedPage);
late SavedMessageTicket replacementInFlight;
storage.onSave = () {
replacementInFlight = saved.capture(oldSaved, _savedPage);
};
await notifier.addCommunity(community.copyWith(nsec: midKeys.nsec));
storage.onSave = null;
expect(container.read(activeCommunityProvider).isLoading, isTrue);
expect(container.read(savedMessageScopeProvider), isNull);
finishActiveRefresh.complete();
await container.read(activeCommunityProvider.future);
expect(container.read(savedMessageScopeProvider), midSaved);
await saved.save(replacementInFlight, [
_savedMessage(oldKeys.secret),
], relayAuthor: null);
expect(await _readSaved(saved, oldSaved), isNull);
await _saveMessage(saved, midSaved, midKeys.secret);
// The next replacement keeps the database the new account wrote first.
await _saveMessage(saved, newSaved, newKeys.secret);
await notifier.addCommunity(community.copyWith(nsec: newKeys.nsec));
await saved.save(oldInFlight, [
_savedMessage(oldKeys.secret),
], relayAuthor: null);
expect(await _readSaved(saved, oldSaved), isNull);
expect(await _readSaved(saved, midSaved), isNull);
expect(await _readSaved(saved, newSaved), hasLength(1));
await notifier.removeCommunity(community.id);
// The active provider still holds the removed account when the list
// publishes; the scope must already be gone.
final scopesDuringRefresh = <SavedMessageScope?>[];
container.listen(communityListProvider, (_, next) {
if (next.value?.isEmpty == true &&
container.read(activeCommunityProvider).value?.id == community.id) {
scopesDuringRefresh.add(container.read(savedMessageScopeProvider));
}
});
await container
.read(communityListProvider.notifier)
.removeCommunity(community.id);
expect(scopesDuringRefresh, [isNull]);
await saved.save(removalInFlight, [
_savedMessage(newKeys.secret),
_savedMessage(oldKeys.secret),
], relayAuthor: null);
expect(await _readSaved(saved, newSaved), isNull);
expect(await _readSaved(saved, oldSaved), isNull);
// No database or journal survives.
expect(Directory('${root.path}/saved_messages').listSync(), isEmpty);
});
@@ -935,14 +869,14 @@ void main() {
revocationTriggers += 1;
return remoteAttempt.future;
};
container = createContainer();
await container.read(communityListProvider.future);
final community = Community.create(
name: 'Test',
relayUrl: 'https://test.example.com',
);
await communityStorage.save(community);
container = createContainer();
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(community);
await notifier.removeCommunity(community.id);
@@ -953,6 +887,11 @@ void main() {
});
test('journal persistence failure keeps community credentials', () async {
final community = Community.create(
name: 'Test',
relayUrl: 'https://test.example.com',
);
await communityStorage.save(community);
container = ProviderContainer(
overrides: [
communityStorageProvider.overrideWithValue(communityStorage),
@@ -968,12 +907,7 @@ void main() {
],
);
await container.read(communityListProvider.future);
final community = Community.create(
name: 'Test',
relayUrl: 'https://test.example.com',
);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(community);
await expectLater(
notifier.removeCommunity(community.id),
@@ -989,9 +923,6 @@ void main() {
test(
'waits for transition teardown before removing active community',
() async {
container = createContainer();
await container.read(communityListProvider.future);
final ws1 = Community.create(
name: 'One',
relayUrl: 'https://one.example.com',
@@ -1000,9 +931,11 @@ void main() {
name: 'Two',
relayUrl: 'https://two.example.com',
);
await communityStorage.save(ws1);
await communityStorage.save(ws2);
container = createContainer();
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(ws1);
await notifier.addCommunity(ws2);
await notifier.switchCommunity(ws1.id);
final teardown = Completer<void>();
container
@@ -1028,9 +961,6 @@ void main() {
);
test('waits for transition teardown before updating active ID', () async {
container = createContainer();
await container.read(communityListProvider.future);
final ws1 = Community.create(
name: 'One',
relayUrl: 'https://one.example.com',
@@ -1039,9 +969,11 @@ void main() {
name: 'Two',
relayUrl: 'https://two.example.com',
);
await communityStorage.save(ws1);
await communityStorage.save(ws2);
container = createContainer();
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(ws1);
await notifier.addCommunity(ws2);
await notifier.switchCommunity(ws1.id);
final teardown = Completer<void>();
container
@@ -1097,9 +1029,6 @@ void main() {
test(
'transition callback failure does not block the active ID update',
() async {
container = createContainer();
await container.read(communityListProvider.future);
final ws1 = Community.create(
name: 'One',
relayUrl: 'https://one.example.com',
@@ -1108,9 +1037,11 @@ void main() {
name: 'Two',
relayUrl: 'https://two.example.com',
);
await communityStorage.save(ws1);
await communityStorage.save(ws2);
container = createContainer();
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(ws1);
await notifier.addCommunity(ws2);
await notifier.switchCommunity(ws1.id);
container.read(communityTransitionProvider).register(() async {
throw StateError('native cleanup failed');
@@ -1123,9 +1054,6 @@ void main() {
);
test('switchCommunity updates active ID', () async {
container = createContainer();
await container.read(communityListProvider.future);
final ws1 = Community.create(
name: 'One',
relayUrl: 'https://one.example.com',
@@ -1135,9 +1063,11 @@ void main() {
relayUrl: 'https://two.example.com',
);
await communityStorage.save(ws1);
await communityStorage.save(ws2);
container = createContainer();
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(ws1);
await notifier.addCommunity(ws2);
await notifier.switchCommunity(ws2.id);
final activeId = await communityStorage.loadActiveId();
@@ -1147,10 +1077,6 @@ void main() {
test('switching and removing name the new member at once', () async {
final reporter = _MemberRecorder();
container = createContainer(
overrides: [diagnosticReporterProvider.overrideWithValue(reporter)],
);
await container.read(communityListProvider.future);
final one = nostr.Keys.generate();
final two = nostr.Keys.generate();
final ws1 = Community.create(
@@ -1163,9 +1089,13 @@ void main() {
relayUrl: 'https://two.example.com',
nsec: two.nsec,
);
await communityStorage.save(ws1);
await communityStorage.save(ws2);
container = createContainer(
overrides: [diagnosticReporterProvider.overrideWithValue(reporter)],
);
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(ws1);
await notifier.addCommunity(ws2);
await notifier.switchCommunity(ws1.id);
expect(reporter.member, one.public);
@@ -1203,8 +1133,6 @@ void main() {
test('a switch whose read fails changes nothing and can retry', () async {
final storage = _FailingLoadStorage(fakeSecure);
communityStorage = storage;
container = createContainer();
final notifier = container.read(communityListProvider.notifier);
final a = Community.create(
name: 'A',
relayUrl: 'https://a.example.com',
@@ -1215,9 +1143,11 @@ void main() {
relayUrl: 'https://b.example.com',
nsec: nostr.Keys.generate().nsec,
);
await communityStorage.save(a);
await communityStorage.save(b);
container = createContainer();
final notifier = container.read(communityListProvider.notifier);
await container.read(communityListProvider.future);
await notifier.addCommunity(a);
await notifier.addCommunity(b);
await notifier.switchCommunity(a.id);
storage.failNextLoad = true;
@@ -1237,15 +1167,14 @@ void main() {
});
test('returns community matching active ID', () async {
container = createContainer();
await container.read(communityListProvider.future);
final ws = Community.create(
name: 'Test',
relayUrl: 'https://test.example.com',
);
await communityStorage.save(ws);
container = createContainer();
await container.read(communityListProvider.future);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(ws);
await notifier.switchCommunity(ws.id);
final active = await container.read(activeCommunityProvider.future);
@@ -1268,15 +1197,13 @@ void main() {
});
test('falls back to first community if active ID is invalid', () async {
container = createContainer();
await container.read(communityListProvider.future);
final ws = Community.create(
name: 'Fallback',
relayUrl: 'https://test.example.com',
);
final notifier = container.read(communityListProvider.notifier);
await notifier.addCommunity(ws);
await communityStorage.save(ws);
container = createContainer();
await container.read(communityListProvider.future);
// Set an invalid active ID.
await communityStorage.saveActiveId('nonexistent-id');
@@ -1400,22 +1327,3 @@ Map<String, dynamic> _descriptorJson(String origin) => {
},
},
};
class _ObservedSaveStorage extends CommunityStorage {
_ObservedSaveStorage(FlutterSecureStorage secure) : super(secure: secure);
void Function()? onSave;
Future<void>? activeReadGate;
@override
Future<String?> loadActiveId() async {
await activeReadGate;
return super.loadActiveId();
}
@override
Future<void> save(Community community) {
onSave?.call();
return super.save(community);
}
}