Files
buzz/mobile/test/features/settings/settings_sign_out_test.dart
Wes f9b18c7f3a Cache recently opened mobile channel pages (#9809)
## What changed

Previously opened channels can show their newest saved page after a cold
launch, including offline. The same timeline provider combines the saved
page with live edits, deletions, and optimistic sends. When the relay
has loaded history, its timeline takes over and older-page navigation
becomes available. The chat labels saved messages until relay history
takes over. If a connected refresh fails, the chat offers Retry and
keeps the saved-message label visible during the retry.

- Keep verified relay events in a disposable, app-private SQLite cache
per community and signing identity on iOS and Android. Close SQLite
connections after each operation.
- Cap the main file at 45 MiB to leave room for a rollback journal
within the 100 MB per-community limit. Evict least-recently opened pages
and retry once when SQLite reaches the physical limit.
- Omit an oversized relay page as a whole so the cache cannot show a
message without an edit or deletion from the same response. Keep
readable pages available when only the recency write fails.
- Purge on leave, deletion, explicit channel access refusal, and
writer-confirmed loss of a known membership. Expired sessions leave the
cache intact. SQLite secure deletion clears removed payloads after
commit. A durable marker covers interrupted purges. Account switches and
removal retire old saves.
- Keep message-link lookups valid across the first connection. An access
refusal still discards a late result.
- After a confirmed leave or delete, record a durable cache purge before
refreshing the channel list. Disk cleanup runs in the background and the
refresh skips redundant writer confirmation for that channel.
- For joined, unarchived channels, remove stale saved rows on
channel-tagged deletions or edits the app receives while the
conversation is closed. Reuse deletions from the existing reconnect
catch-up.
- Give an already-connected relay one 250 ms head start before reading
the saved page. Offline opens start the read immediately.

## Screenshots and timing

[iPhone 17e simulator
captures](https://github.com/block/buzz/pull/9809#issuecomment-7050704433)
show the same seeded chat before the cache, with saved messages while
offline, and after the relay returns. In the debug capture run, the
baseline `9c0bcd623` showed no messages within 8 seconds. The updated
build `2cb28eda` showed the target saved message **752 ms** after the
tap.

For a first online open on the same simulator, the baseline and the
instrumented `2cb28eda` build took **449 ms** and **441 ms** median from
tap to target message. Each build had four measured opens after one
warm-up. The ranges were 437–481 ms and 414–447 ms.

In the earlier paired debug simulator experiment on `6e113d83`, the 250
ms preview delay reduced median first online open from **507 ms to 452
ms** across 15 measured opens per build. In the delay build, seeded
offline opens took **488–557 ms** across the two channel medians, and
reopens in the same app session took **174–245 ms**. All 20 offline
opens and reopens showed the target message.

## Verification

- The mobile pre-push gate and file-size check passed for `6650ebad`.
Regression tests cover oversized pages, session expiry versus channel
revocation, live mutations during preview, paging after relay history
loads, writer-confirmed membership loss, closed-chat edits and
deletions, the saved-message label across Retry and history takeover,
links held across first connect, and interrupted or overlapping purges.
- The host SQLite probe interrupted eviction, relay-key rotation, and a
synthetic table rewrite. All three reopened with a clean integrity
check. The largest observed database and journal footprint was 93.84 MB.
- Physical iPhone suspension, airplane-mode reopen, and profile-mode
timing are pending.

## Try it

1. While connected, open a populated channel and let its newest page
save.
2. Force-quit, turn on airplane mode, and reopen the same channel. The
saved page should appear.
3. Reconnect. The relay's newest page should take over without
duplicating messages.

A saved page can still show stale rows while the phone stays offline,
for a live edit missed while the app was stopped, for an archived or
unjoined public channel, or for a NIP-09 deletion without a channel tag.
Reconnect catch-up covers the deletions returned by its bounded unread
query. A direct online open refreshes the page. Offline thread replies
are separate follow-up work.

---------

Signed-off-by: Wes <wesb@block.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz>
Co-authored-by: Mantis <530af7635ef7d0e1a5189d234338db88cb4ef1ede7119b4ebb4fb05c3eafe3b1@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 16:03:27 -07:00

383 lines
14 KiB
Dart

import 'dart:async';
import 'dart:io';
import 'package:buzz/features/settings/settings_page.dart';
import 'package:buzz/hosted_app_gate.dart';
import 'package:buzz/onboarding_app_entry.dart';
import 'package:buzz/shared/auth/auth.dart';
import 'package:buzz/shared/channels/saved_message_store.dart';
import 'package:buzz/shared/crypto/event_signing.dart';
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
import 'package:buzz/shared/hosted/account_identity_store.dart';
import 'package:buzz/shared/hosted/hosted_environment.dart';
import 'package:buzz/shared/hosted/hosted_flow_provider.dart';
import 'package:buzz/shared/relay/nostr_models.dart';
import 'package:buzz/shared/relay/relay_session.dart';
import 'package:buzz/shared/theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nostr/nostr.dart' as nostr;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../helpers/hosted_communities_fixture.dart';
/// Runs in every build. A public build also signs out of Builderlab:
/// `--dart-define=BUZZ_DISTRIBUTION=public`
/// `--dart-define=BUZZ_BUILDERLAB_URL=https://app.builderlab.xyz`
/// `--dart-define=BUZZ_BUILDERLAB_RELAYS=communities.buzz.xyz`
void main() {
testWidgets(
'Sign out removes every community but keeps each key on this device',
(tester) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = const Size(390, 1600);
addTearDown(tester.view.reset);
FlutterSecureStorage.setMockInitialValues({});
SharedPreferences.setMockInitialValues({});
PackageInfo.setMockInitialValues(
appName: 'Buzz',
packageName: 'xyz.block.buzz',
version: '0.16.0',
buildNumber: '1',
buildSignature: '',
);
final prefs = await SharedPreferences.getInstance();
// Neither key is exported or backed up anywhere.
final activeKeys = nostr.Keys.generate();
final otherKeys = nostr.Keys.generate();
final active = Community.create(
name: 'Active',
relayUrl: 'wss://active.example.org',
nsec: activeKeys.nsec,
);
final other = Community.create(
name: 'Other',
relayUrl: 'wss://other.example.org',
nsec: otherKeys.nsec,
);
final storage = CommunityStorage();
await storage.save(active);
await storage.save(other);
await storage.saveActiveId(active.id);
// Deleting saved messages needs real async time, which also lets these
// app streams subscribe.
final messenger = tester.binding.defaultBinaryMessenger;
for (final name in [
'com.llfbandit.app_links/events',
'dev.fluttercommunity.plus/connectivity_status',
]) {
final channel = EventChannel(name);
messenger.setMockStreamHandler(
channel,
MockStreamHandler.inline(onListen: (_, _) {}),
);
addTearDown(() => messenger.setMockStreamHandler(channel, null));
}
// Both accounts have saved messages from an earlier launch.
final savedRoot = (await tester.runAsync(
() => Directory.systemTemp.createTemp('saved_root'),
))!;
addTearDown(() => savedRoot.delete(recursive: true));
final savedMessages = Directory('${savedRoot.path}/saved_messages');
await tester.runAsync(() async {
final launch = SavedMessageStore(
root: () async => savedRoot,
diagnostics: const NoopDiagnosticReporter(),
);
for (final (community, keys) in [
(active, activeKeys),
(other, otherKeys),
]) {
final scope = (communityId: community.id, pubkey: keys.public);
final ticket = launch.capture(scope, _savedPage);
await launch.save(ticket, [
_savedMessage(keys.secret),
], relayAuthor: null);
expect(
await launch.read(launch.capture(scope, _savedPage)),
hasLength(1),
);
}
});
expect(savedMessages.listSync(), isNotEmpty);
HostedCommunitiesFixture? hosted;
final accountStorage = _AccountStorage();
if (HostedEnvironment.enabled) {
hosted = HostedCommunitiesFixture();
// A later launch whose session restore hasn't succeeded yet: the
// session is saved but not in memory.
await hosted.initialize(
accountStorage: accountStorage,
coldAccount: true,
);
addTearDown(hosted.dispose);
await hosted.flow.leave();
hosted.unavailable = true;
await expectLater(hosted.account.restore(), throwsA(anything));
expect(hosted.account.account, isNull);
}
// Hosted setup must never cover Settings while it signs out.
final pushes = _Pushes();
// The Builderlab session must be gone before the Sign in landing can
// show it or be interrupted by its end.
final sessionAtRemoval = <bool>[];
final removed = <String>[];
late SavedMessageStore cache;
late SavedMessageTicket signOutInFlight;
// Revocations stay in flight until the landing has been checked.
final revocations = Completer<void>();
addTearDown(() {
if (!revocations.isCompleted) revocations.complete();
});
await tester.pumpWidget(
ProviderScope(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
communityStorageProvider.overrideWithValue(storage),
communitySnapshotWriterProvider.overrideWithValue((_) async {}),
communityPushLeaseRevocationEnqueuerProvider.overrideWithValue((
community,
) async {
removed.add(community.id);
sessionAtRemoval.add(hosted?.account.account != null);
if (community.id == active.id) {
signOutInFlight = cache.capture((
communityId: active.id,
pubkey: activeKeys.public,
), _savedPage);
}
return true;
}),
communityPushLeaseRevocationTriggerProvider.overrideWithValue(
() => revocations.future,
),
relaySessionProvider.overrideWith(_OfflineSession.new),
savedMessageRootProvider.overrideWith((ref) async => savedRoot),
if (hosted != null)
hostedFlowProvider.overrideWithValue(hosted.flow),
],
child: MaterialApp(
theme: AppTheme.light(),
navigatorObservers: [pushes],
home: const _Root(),
),
),
);
await tester.pumpAndSettle();
cache = ProviderScope.containerOf(
tester.element(find.byType(_Root)),
).read(savedMessageStoreProvider);
await tester.tap(find.text('Open Settings'));
await tester.pumpAndSettle();
// Cancelling keeps everything.
await tester.tap(find.byKey(const Key('settings-sign-out')));
await tester.pumpAndSettle();
expect(find.text('Sign out?'), findsOneWidget);
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(await storage.loadAll(), hasLength(2));
expect(savedMessages.listSync(), isNotEmpty);
Future<void> confirmSignOut() async {
await tester.tap(find.byKey(const Key('settings-sign-out')));
await tester.pumpAndSettle();
pushes.count = 0;
await tester.tap(find.widgetWithText(FilledButton, 'Sign out'));
}
// Each failure keeps every community and shows its error in Settings.
Future<void> signOutFails() async {
await confirmSignOut();
await tester.pumpAndSettle();
expect(pushes.count, 0);
expect(find.byType(SettingsPage), findsOneWidget);
expect(find.textContaining('Failed to sign out'), findsOneWidget);
expect(await storage.loadAll(), hasLength(2));
expect(removed, isEmpty);
ScaffoldMessenger.of(
tester.element(find.byKey(const Key('settings-sign-out'))),
).removeCurrentSnackBar();
await tester.pumpAndSettle();
}
if (hosted != null) {
// The saved session can't be deleted, though it isn't restored yet.
accountStorage.failing = true;
await signOutFails();
hosted.unavailable = false;
expect(await hosted.account.restore(), isNotNull);
// Nor once it is.
await signOutFails();
expect(hosted.account.account, isNotNull);
accountStorage.failing = false;
// A pending browser sign-in can't be forgotten.
hosted.browser.clearIntentError = PlatformException(code: 'keychain');
await signOutFails();
expect(hosted.account.account, isNotNull);
hosted.browser.clearIntentError = null;
}
// A session check still pending must not hold up signing out, nor
// restore the session when it finishes afterwards.
final heldCheck = Completer<void>();
Future<Object?>? pendingRestore;
if (hosted != null) {
hosted.beforeMe = () => heldCheck.future;
pendingRestore = hosted.account.restore().then<Object?>(
(restored) => restored,
onError: (Object error) => error,
);
await tester.pump();
}
addTearDown(() {
if (!heldCheck.isCompleted) heldCheck.complete();
});
await confirmSignOut();
// Saved messages are deleted on a real worker isolate before each
// community's credentials.
for (
var i = 0;
i < 100 && find.byType(SettingsPage).evaluate().isNotEmpty;
i++
) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 10)),
);
await tester.pump();
}
// The landing animates, so it never settles.
await _pumpFor(tester);
expect(pushes.count, 0);
expect(await storage.loadAll(), isEmpty);
expect(find.byType(SettingsPage), findsNothing);
expect(find.byType(OnboardingAppEntry), findsOneWidget);
expect(find.textContaining('Signed in as'), findsNothing);
// The active community goes last, so nothing switches to the other.
expect(removed, [other.id, active.id]);
await tester.runAsync(
() => cache.save(signOutInFlight, [
_savedMessage(activeKeys.secret),
], relayAuthor: null),
);
// Even a refresh started during sign-out cannot recreate the database.
expect(savedMessages.listSync(), isEmpty);
final saved = await AccountIdentityStore().identities();
expect(
saved.map((identity) => identity.pubkey),
containsAll([activeKeys.public, otherKeys.public]),
);
if (hosted != null) {
expect(sessionAtRemoval, everyElement(isFalse));
expect(hosted.account.account, isNull);
heldCheck.complete();
expect(await pendingRestore, isNull);
expect(hosted.account.account, isNull);
expect(await hosted.account.restore(), isNull);
}
// Revocations finishing later change nothing on the landing.
revocations.complete();
await _pumpFor(tester);
expect(find.byType(OnboardingAppEntry), findsOneWidget);
expect(find.textContaining('Signed in as'), findsNothing);
expect(hosted?.account.account, isNull);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink());
await _pumpFor(tester);
},
);
}
const _savedPage = (channelId: 'saved-channel', rootId: '');
NostrEvent _savedMessage(String secret) => NostrEvent.fromJson(
signNostrEvent(
kind: EventKind.streamMessage,
content: 'saved message',
secretKey: secret,
createdAt: 1700000000,
tags: [
['h', _savedPage.channelId],
],
).toMap(),
);
Future<void> _pumpFor(WidgetTester tester) async {
for (var i = 0; i < 20; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
/// Fails to delete the Builderlab session while [failing], as an unavailable
/// Keychain would.
class _AccountStorage extends FlutterSecureStorage {
bool failing = false;
@override
Future<void> delete({
required String key,
AppleOptions? iOptions,
AndroidOptions? aOptions,
LinuxOptions? lOptions,
WebOptions? webOptions,
AppleOptions? mOptions,
WindowsOptions? wOptions,
}) {
if (failing && key.startsWith('buzz_hosted_session_')) {
throw PlatformException(code: 'keychain', message: 'unavailable');
}
return super.delete(key: key);
}
}
/// Swaps in the Sign in landing once the device is signed out, as the app does.
class _Root extends ConsumerWidget {
const _Root();
@override
Widget build(BuildContext context, WidgetRef ref) {
final status = ref.watch(authProvider).value?.status;
if (status == null) return const SizedBox.shrink();
if (status != AuthStatus.authenticated) return const OnboardingAppEntry();
return HostedAppGate(
authenticated: true,
child: Scaffold(
body: TextButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => SettingsPage(
profileHeader: const SizedBox.shrink(),
identityRecoveryPageBuilder: (_) => const SizedBox.shrink(),
),
),
),
child: const Text('Open Settings'),
),
),
);
}
}
/// The relay boundary: nothing connects.
class _OfflineSession extends RelaySessionNotifier {
@override
SessionState build() =>
const SessionState(status: SessionStatus.disconnected);
}
/// Counts routes pushed since [count] was last reset.
class _Pushes extends NavigatorObserver {
int count = 0;
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) => count++;
}