Files
buzz/mobile/test/features/channels/channels_provider_request_path_cases.dart
Wes ab73cd9fb5 perf(mobile): restore cached channels before community sync (#8580)
## Summary

Returning to a previously visited community shows its saved channel list
immediately, including offline, while membership and unread state
refresh in the background. Initial revalidation failures keep the list
visible and retry every 60 seconds without overlapping background
attempts. After successful history revalidation, ordinary reconnects use
metadata-only refreshes. A reconnect arriving during a background
request queues one follow-up attempt; timer ticks never queue
overlapping work. History deadlines retain the full-revalidation retry
until history succeeds.

Snapshots are disposable, versioned and scoped by canonical relay URL
and signing identity, capped at 2 MB / 2,000 member channels. They
include hidden-DM IDs and prefer fresher in-memory state. Community
removal and identity replacement retire outstanding writes; re-adding
unchanged credentials preserves the current cache and writer. Startup
sweeps orphan snapshots without waiting for disk acknowledgement;
community mutations also sweep orphan snapshots, including data restored
without secure community records. Cache-delete failures do not block
sign-out or strand push revocation; deletion is attempted before
journaling and retried by orphan cleanup. Successfully persisted
unchanged snapshots skip disk writes; failed writes remain retryable.

The cold path reuses fetched membership rosters, overlaps
profile/latest-message requests, shares verified DM profiles with
avatars, and fetches the own profile once per authenticated connection.
Community connection work overlaps the switching animation; avatar
hydration no longer gates landing. Full channel refreshes also
revalidate cached DM participant profiles so relay-side name changes
reach labels and avatars; metadata-only reconnects and background
refreshes reuse admitted profiles.

Me-chat and invite starter recovery use an explicit fresh membership
fetch that propagates errors while leaving the cached list visible.
Cached layout/read preferences permit immediate landing; newer
cross-device preferences may update ordering or badges after reveal.

Integrated with main’s #8490 idle/resume changes: hidden chats detach
live subscriptions, background membership polling stays quiet, and each
resume reconciles once. Chat history follows main’s live-admission-first
ordering to avoid missing messages committed during relay admission;
cached community landing remains immediate.

## Validation

- `just mobile-install mobile-check mobile-test`: clean analysis; 3,778
tests passed, 19 skipped; four checks for builds without push
configuration passed. File-size and diff checks passed.
- Provider/storage journeys cover offline startup, failed initial
revalidation recovering live delivery, bounded retries, lightweight
reconnects, scope isolation, default-port URLs, padded/mismatched stored
credentials, credential replacement, backup-restored orphan data,
removal races, failed platform deletes and failed writes.
- Follow-up regressions cover interrupted native Me-chat lookup, invite
failure propagation, retry after an initial list failure, history
deadlines, queued reconnects, escaped-path keys, unchanged credential
re-adds and non-blocking startup cleanup. Reverting each of the eight
behavior/caller/cleanup-order fixes fails its corresponding regression.
- DM-name regression changes only the relay profile, verifies a full
refresh updates the channel label and shared profile cache, and confirms
ordinary reconnects avoid another profile request. The original
cache-only implementation fails this regression.
- Original signed-in iPhone 18 Pro debug simulator measurements: Buzz's
413 channels went from 6.26–6.30 s to approximately 1.5 s on returning;
all three warmed communities switched in 1.47–1.54 s. Real socket pause
restored the cached list offline and retained it on reconnect. These are
debug simulator observations, not release-device benchmarks.
- Integration with current main also passes the real-session
resume/background/AUTH and live-admission/detach journeys.
- Follow-up failure paths were exercised with deterministic
provider/storage tests and widget journeys; the running simulator was
not modified during this follow-up.

Human acceptance remains pending; this PR stays draft. Try switching
among previously visited communities, opening a channel, restarting and
repeating. First visits and oversized snapshots require network loading.
Cached metadata can be stale until refresh; it lives in ordinary
preferences without additional application-level encryption. The
snapshot contains no message bodies or credentials. Persistent
disk-deletion failures can leave metadata until a later cleanup
succeeds.

---------

Signed-off-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz>
Co-authored-by: Groot <f4c08302591916fb4b80926bf7e18d22eef8aa0c877e4e841acc46405a45700b@buzz.block.builderlab.xyz>
Co-authored-by: Mantis <530af7635ef7d0e1a5189d234338db88cb4ef1ede7119b4ebb4fb05c3eafe3b1@buzz.block.builderlab.xyz>
2026-10-26 11:57:07 -06:00

290 lines
8.5 KiB
Dart

part of 'channels_provider_test.dart';
void _requestPathCases() {
test('DM hydration overlaps history and shares admitted profiles', () async {
final session = _RequestPathSession();
final profilesGate = session.profilesGate = Completer<void>();
final latestGate = session.latestGate = Completer<void>();
final container = _buildContainer(session: session);
addTearDown(container.dispose);
final load = container.read(channelsProvider.future);
await _settle();
expect(session.profileRequests, 1);
expect(session.latestRequests, 1);
expect(container.read(channelsProvider).hasValue, isFalse);
final cacheReady = Completer<void>();
final cacheSubscription = container.listen(userCacheProvider, (_, next) {
if (next.containsKey('alice') && !cacheReady.isCompleted) {
cacheReady.complete();
}
});
addTearDown(cacheSubscription.close);
profilesGate.complete();
await cacheReady.future;
expect(container.read(channelsProvider).hasValue, isFalse);
latestGate.complete();
final channel = (await load).single;
expect(channel.displayLabel(currentPubkey: 'me'), 'Alice');
expect(channel.memberCount, 2);
expect(channel.lastMessageAt?.millisecondsSinceEpoch, 50000);
expect(
container.read(userCacheProvider)['alice']?.avatarUrl,
'https://example.com/alice.png',
);
expect(
await container.read(userCacheProvider.notifier).preload(['alice']),
isTrue,
);
expect(session.profileRequests, 1);
// Full refreshes discover relay-side profile changes without another
// surface injecting a live cache event. Blank names retain the fallback.
session.profiles = [
_requestProfile(
'alice',
name: ' ',
handle: ' alice@example.com ',
createdAt: 2,
),
];
// Ordinary reconnects stay metadata-only and reuse the admitted profile.
session.setStatus(SessionStatus.disconnected);
await _settle();
session.setStatus(SessionStatus.connected);
await _settle();
expect(session.profileRequests, 1);
expect(
container
.read(channelsProvider)
.requireValue
.single
.displayLabel(currentPubkey: 'me'),
'Alice',
);
await container.read(channelsProvider.notifier).refresh();
expect(
container
.read(channelsProvider)
.requireValue
.single
.displayLabel(currentPubkey: 'me'),
'alice@example.com',
);
expect(session.profileRequests, 2);
expect(
container.read(userCacheProvider)['alice']?.nip05Handle?.trim(),
'alice@example.com',
);
session.profiles = [
_requestProfile('alice', name: ' ', handle: ' ', createdAt: 3),
];
await container.read(channelsProvider.notifier).refresh();
expect(
container
.read(channelsProvider)
.requireValue
.single
.displayLabel(currentPubkey: 'me'),
'Unknown identity',
);
expect(session.profileRequests, 3);
});
test(
'late DM profiles cannot enter the destination cache or channel list',
() async {
final session = _RequestPathSession();
final profilesGate = session.profilesGate = Completer<void>();
final container = _buildContainer(session: session);
addTearDown(container.dispose);
final oldLoad = container.read(channelsProvider.future);
await _settle();
expect(session.profileRequests, 1);
session.profiles = [_requestProfile('alice', name: 'Destination Alice')];
container
.read(relayConfigProvider.notifier)
.update(baseUrl: 'https://destination.example');
final destination = await container.read(channelsProvider.future);
expect(
destination.single.displayLabel(currentPubkey: 'me'),
'Destination Alice',
);
profilesGate.complete();
await oldLoad;
await _settle();
expect(
container.read(userCacheProvider)['alice']?.displayName,
'Destination Alice',
);
expect(
container
.read(channelsProvider)
.requireValue
.single
.displayLabel(currentPubkey: 'me'),
'Destination Alice',
);
},
);
test(
'DM profile failures propagate while concurrent history is pending',
() async {
final failure = StateError('profile request failed');
final session = _RequestPathSession()..profileFailure = failure;
final latestGate = session.latestGate = Completer<void>();
final container = _buildContainer(session: session);
addTearDown(container.dispose);
await expectLater(
container.read(channelsProvider.future),
throwsA(same(failure)),
);
expect(session.latestRequests, 1);
latestGate.complete();
await _settle();
expect(container.read(channelsProvider).error, same(failure));
},
);
test(
'latest discovered roster owns Huddle filtering and member counts',
() async {
final session = _FakeRelaySession(
memberships: [
_membership(
_channelA,
'me',
additionalPubkey: 'alice',
createdAt: 2,
eventId: 'new-a',
),
_membership(
_channelB,
'me',
ownerPubkey: 'me',
createdAt: 2,
eventId: 'new-b',
),
_membership(_channelA, 'me', eventId: 'old-a'),
_membership(
_channelB,
'me',
ownerPubkey: 'imposter',
eventId: 'old-b',
),
],
metadata: [
_meta(id: _channelA, name: 'General'),
_meta(id: _channelB, name: 'Huddle', visibility: 'private'),
],
huddleStarts: [
_huddleStart(pubkey: 'me', parent: _channelA, backing: _channelB),
],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
final channels = await container.read(channelsProvider.future);
expect(channels.single.id, _channelA);
expect(channels.single.memberCount, 2);
expect(
container
.read(channelsProvider.notifier)
.cachedMembersForChannel(_channelA)
.map((member) => member.pubkey),
['me', 'alice'],
);
},
);
}
NostrEvent _requestProfile(
String pubkey, {
required String name,
String? handle,
int createdAt = 1,
}) => NostrEvent(
id: 'profile-$pubkey-$createdAt',
pubkey: pubkey,
createdAt: createdAt,
kind: 0,
tags: const [],
content: jsonEncode({
'display_name': name,
'nip05': handle,
'picture': 'https://example.com/$pubkey.png',
}),
sig: 'sig',
);
class _RequestPathSession extends _FakeRelaySession {
_RequestPathSession()
: super(
memberships: [_membership(_channelA, 'me', additionalPubkey: 'alice')],
metadata: [
_meta(
id: _channelA,
name: 'DM',
channelType: 'dm',
participants: ['me', 'alice'],
),
],
recentMessages: const [
NostrEvent(
id: 'dm-latest',
pubkey: 'alice',
createdAt: 50,
kind: 9,
tags: [
['h', _channelA],
],
content: 'Hello',
sig: 'sig',
),
],
);
List<NostrEvent> profiles = [_requestProfile('alice', name: 'Alice')];
Completer<void>? profilesGate;
Completer<void>? latestGate;
Object? profileFailure;
int profileRequests = 0;
int latestRequests = 0;
@override
Future<List<NostrEvent>> fetchHistory(
NostrFilter filter, {
Duration timeout = const Duration(seconds: 8),
}) async {
if (!filter.kinds.contains(0)) {
return super.fetchHistory(filter, timeout: timeout);
}
profileRequests++;
final snapshot = List<NostrEvent>.of(profiles);
final gate = profilesGate;
profilesGate = null;
await gate?.future;
if (profileFailure case final failure?) throw failure;
return snapshot;
}
@override
Future<List<NostrEvent>> queryRelay(
List<NostrFilter> filters, {
Duration timeout = const Duration(seconds: 8),
}) async {
if (filters.isNotEmpty &&
filters.every(
(filter) => filter.kinds.contains(9) && filter.since == null,
)) {
latestRequests++;
final gate = latestGate;
latestGate = null;
await gate?.future;
}
return super.queryRelay(filters, timeout: timeout);
}
}