Files
buzz/mobile/test/features/channels/quick_send_test.dart
Tom Brow e600cdbde2 feat(mobile): time channel opens and relay connection recovery (#9858)
Adds two durations to the mobile networking diagnostics, so work on
channel opening and reconnecting has a before and after number from real
use:

- **Channel open** (`channelOpen`): from asking for a channel's newest
history to the messages being shown, or to the failure that stopped it
(including a refusal on the live subscription, or one a thread screen
reports, which counts as a failed open with no duration when it comes
before the history was asked for). Only a channel's first load counts; a
catch-up after a reconnect is not an open. An open cut short by a lost
connection keeps its clock, so the wait for the reconnect counts. An
open that spans a move to the background, or starts there, is not
counted, since it measured the time away, and a return after leaving the
channel or after the background is a new open. An open the member backed
out of still counts, since the load took that long, unless they left
while a lost connection was still reconnecting, before its history was
asked for again; after a failed open a retry counts as a new one. A
refusal that arrives after a move to the background is not counted
either: whether a refusal can count is fixed when the load starts. An
open is filed under the member whose relay it ran on, and not counted
when the app has since moved to another member.
- **Relay recovery** (`relayRecovery`): from the last frame a lost
connection delivered to the next authenticated connection. Starting at
the last frame means the time it took to notice a dead socket counts
too, which the existing connect duration misses. The app cannot see
pongs, so a quiet connection is taken to have been alive until two ping
intervals (60 s) before the loss, and idle time does not inflate the
number by more than that: an idle connection that closes cleanly can
read up to a minute, since a clean close and a missed ping look the same
to the app. Failed attempts in between are part of one recovery. A loss
in the background or followed by a move to the background, and a loss
carried across a community switch, are not counted. A loss in the first
seconds after a return from a brief stay in the background can reach
back to before the stay, by at most that same minute.

Both durations run on a monotonic clock, so a correction of the device's
clock during an open or an outage does not inflate a sample or make it
negative.

Both go through the existing `network.event` count and
`network.duration` distribution with their endpoint name, like the other
networking events.

### Regressions

None expected. These add no requests: each is one counted event per
channel open or per recovered connection, recorded where the app already
counts connection events.

### Validation

Read from a profile build on an iPhone 12 mini against a hosted relay,
with a local log of each event:

- Seven channel opens after a cold start: `channelOpen` read 0.36 to
1.48 s per open, each matching the time from the history request to its
response in the request log.
- Three Wi-Fi drops of about 22 s with a channel open: `relayRecovery`
read 30.1, 47.0 and 30.4 s, each spanning the drop, the time until the
dead socket was noticed, and the reconnect. `relayConnection` alone read
0.28 to 0.36 s for the same reconnects, so the new duration is what
shows the time lost to the dead socket.

That run also covered the flows this touches: cold start, opening
channels with back navigation, and losing and regaining the network with
a channel open. Every open and every reconnect completed.

Added tests:

-
[relay_network_counts_test.dart](mobile/test/shared/relay/relay_network_counts_test.dart):
recovery is timed from the last frame, at most two ping intervals back,
spans failed attempts, is not moved by a device clock set forward or
back during the outage, and is not counted for the background or a
community switch; existing journeys now expect a recovery after each
loss.
-
[channel_open_timing_test.dart](mobile/test/features/channels/channel_open_timing_test.dart):
an open is timed once, to its history being shown; a reconnect catch-up
is not an open; an open spanning a reconnect keeps its start; a member
change during the open, or an open started after the app moved to
another member, records nothing; backing out still records it; a return
after leaving starts a new clock; an open spanning a stay in the
background, or started there, records nothing; a live refusal records a
failed open, once, with its time when the member already backed out and
with no duration when it comes before the history request; a refused
retry after a failed open is a new open; a refusal on reconnect ends an
open cut short by the lost connection with its full wait, or with no
duration if the app was in the background meanwhile; a refusal that
arrives before the history is asked for counts in the foreground and
records nothing after a move to the background; a refusal reported by a
thread screen ends a first open as one refused open, timed once the
history was asked for, records nothing after a move to the background,
and is not another open once the channel has loaded; a device clock set
forward or back during an open does not move its time; a relay deadline
is a timeout.

Known limits:

- The device run predates the final review commits, which changed which
opens are counted (background, member switch, refusals) and moved both
durations to a monotonic clock, not where an open or recovery starts or
ends.
- iOS Siri Quick Send tells the relay session the app is back in the
foreground while it sends. A Quick Send to a DM whose messages were
never loaded this run can count one open, and a connection lost during
the send can count a recovery. Both are true first-load and recovery
times, at most one open per DM per run. Moving Quick Send onto the
background-work hold would remove both, which changes Quick Send and is
left out of this PR.
- When a saved page of a channel is already on screen, `channelOpen`
measures how long fresh history took rather than how long the member
waited to see anything, and it ends when the messages are handed to the
screen, not at the first frame that draws them.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-23 12:22:14 -08:00

362 lines
11 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:buzz/shared/drafts/compose_drafts_provider.dart';
import 'package:buzz/features/channels/channel.dart';
import 'package:buzz/features/channels/channels_provider.dart';
import 'package:buzz/features/channels/quick_send_host.dart';
import 'package:buzz/shared/me/default_agent.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:buzz/shared/theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nostr/nostr.dart' as nostr;
import 'package:shared_preferences/shared_preferences.dart';
class _EmptyChannels extends ChannelsNotifier {
@override
Future<List<Channel>> build() async => [];
}
class _Lifecycle extends AppLifecycleNotifier {
@override
AppLifecycleState build() => AppLifecycleState.resumed;
void background() => state = AppLifecycleState.paused;
}
class _Config extends RelayConfigNotifier {
_Config(this.config);
final RelayConfig config;
@override
RelayConfig build() => config;
}
/// A relay that is not connected until the test says so, accepts every
/// publish and serves back the DM its open command finds or creates.
class _Relay extends RelaySessionNotifier {
_Relay(this.owner);
final nostr.Keys owner;
final published = <NostrEvent>[];
/// Rejects the next message the way an over-quota relay does.
var rateLimitNextMessage = false;
/// Loses the next message's answer, so it may or may not have landed.
var timeOutNextMessage = false;
/// Drops the socket just before the next message goes out.
var dropBeforeNextMessage = false;
final _stored = <NostrEvent>[];
static const dmId = 'bestie-dm';
@override
SessionState build() =>
const SessionState(status: SessionStatus.disconnected);
void connect() => state = const SessionState(status: SessionStatus.connected);
/// Background pauses started; the real session closes the socket after one.
@override
var pauses = 0;
@override
void onAppPaused() => pauses++;
@override
void onAppResumed() => connect();
NostrEvent _sign(int kind, List<List<String>> tags) => NostrEvent.fromJson(
nostr.Event.from(
kind: kind,
content: '',
secretKey: owner.secret,
tags: tags,
).toMap(),
);
@override
Future<List<NostrEvent>> queryRelay(
List<NostrFilter> filters, {
Duration timeout = const Duration(seconds: 8),
}) async => const [];
@override
Future<List<NostrEvent>> fetchHistory(
NostrFilter filter, {
Duration timeout = const Duration(seconds: 8),
}) async {
final ds = filter.tags['#d'];
return _stored.reversed
.where(
(e) =>
filter.kinds.contains(e.kind) &&
(ds == null || ds.contains(e.getTagValue('d'))),
)
.take(filter.limit)
.toList();
}
@override
Future<void Function()> subscribeWithStatus(
NostrFilter filter,
void Function(NostrEvent) onEvent, {
void Function(String message)? onClosed,
required void Function(RelaySubscriptionStatus status) onStatusChanged,
bool resumeSince = true,
}) async => () {};
@override
Future<NostrEvent> publish(
NostrEvent event, {
Duration timeout = const Duration(seconds: 8),
Future<bool> Function()? mayPublish,
}) async {
if (event.kind == 9 && rateLimitNextMessage) {
rateLimitNextMessage = false;
throw Exception('rate-limited: quota exceeded; retry in 0s');
}
if (event.kind == 9 && dropBeforeNextMessage) {
dropBeforeNextMessage = false;
throw StateError('Relay session is not connected');
}
if (event.kind == 9 && timeOutNextMessage) {
timeOutNextMessage = false;
throw TimeoutException('no OK');
}
published.add(event);
if (event.kind != 41010) return event;
// Opening is find-or-create: the relay answers with the one DM.
if (!_stored.any((e) => e.getTagValue('d') == dmId)) {
final peer = event.getTagValue('p')!;
_stored.add(
_sign(39000, [
['d', dmId],
['name', 'DM'],
['t', 'dm'],
['private'],
['hidden'],
['p', owner.public],
['p', peer],
]),
);
_stored.add(
_sign(39002, [
['d', dmId],
['p', owner.public, '', 'member'],
['p', peer, '', 'bot'],
]),
);
}
return NostrEvent(
id: event.id,
pubkey: event.pubkey,
createdAt: event.createdAt,
kind: event.kind,
tags: event.tags,
content: 'response:${jsonEncode({'channel_id': dmId, 'created': true})}',
sig: event.sig,
);
}
}
void main() {
testWidgets('Siri quick send posts in the Bestie DM', (tester) async {
const channel = MethodChannel('buzz/quick_send');
final platformCalls = <String>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
call,
) async {
platformCalls.add(call.method);
return null;
});
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
channel,
null,
),
);
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
final owner = nostr.Keys.generate(), bestie = nostr.Keys.generate();
final relay = _Relay(owner);
String? chosenBestie;
await tester.pumpWidget(
ProviderScope(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
relayConfigProvider.overrideWith(
() => _Config(
RelayConfig(baseUrl: 'https://relay.test', nsec: owner.nsec),
),
),
relaySessionProvider.overrideWith(() => relay),
defaultAgentProvider.overrideWith(
(ref) => Stream.value(chosenBestie),
),
channelsProvider.overrideWith(_EmptyChannels.new),
appLifecycleProvider.overrideWith(_Lifecycle.new),
],
child: MaterialApp(
theme: AppTheme.light(),
home: const QuickSendHost(),
),
),
);
await tester.pumpAndSettle();
expect(platformCalls, ['ready'], reason: 'Siri can send once Home is up');
// Siri calls the host the way QuickSend.swift does and gets its reply.
Future<(Object?, PlatformException?)> siri(
String method, [
Object? arguments,
]) async {
Object? result;
PlatformException? failure;
var replied = false;
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
channel.name,
channel.codec.encodeMethodCall(MethodCall(method, arguments)),
(reply) {
try {
result = channel.codec.decodeEnvelope(reply!);
} on PlatformException catch (e) {
failure = e;
}
replied = true;
},
);
for (var i = 0; i < 100 && !replied; i++) {
await tester.pump(const Duration(milliseconds: 50));
}
expect(replied, isTrue, reason: '$method never answered');
return (result, failure);
}
final container = ProviderScope.containerOf(
tester.element(find.byType(QuickSendHost)),
);
container.read(relaySessionProvider);
relay.connect();
await tester.pump();
final (_, noBestie) = await siri('bestie');
expect(noBestie?.code, 'failed');
expect(noBestie?.message, 'Choose a Bestie in Buzz first.');
chosenBestie = bestie.public;
container.invalidate(defaultAgentProvider);
await tester.pump();
final (named, _) = await siri('bestie');
final scope = (named! as Map)['scope'];
expect(named, {'pubkey': bestie.public, 'scope': scope});
// A Bestie looked up before a community switch can't send here.
final (_, switched) = await siri('send', {
'text': 'Remind me to call Sam',
'bestie': bestie.public,
'scope': 'https://other.test $scope',
});
expect(switched?.message, contains('switched communities'));
final (_, blank) = await siri('send', {
'text': ' \n ',
'bestie': bestie.public,
'scope': scope,
});
expect(blank?.code, 'failed');
expect(blank?.message, 'Say a message.');
expect(relay.published, isEmpty);
// Buzz sat in the background long enough for its socket to close.
(container.read(appLifecycleProvider.notifier) as _Lifecycle).background();
relay.state = const SessionState(status: SessionStatus.disconnected);
final pausesBefore = relay.pauses;
// Its catch-up used the write quota, so the first try is turned away.
relay.rateLimitNextMessage = true;
await tester.pumpAndSettle();
final (_, failure) = await siri('send', {
'text': ' Remind me to call Sam ',
'bestie': bestie.public,
'scope': scope,
});
expect(failure, isNull);
expect(
relay.pauses,
pausesBefore + 1,
reason: 'The send hands the session back to its background pause',
);
final open = relay.published.singleWhere((e) => e.kind == 41010);
expect(open.pubkey, owner.public);
expect(open.tags, [
['p', bestie.public],
]);
final first = relay.published.singleWhere((e) => e.kind == 9);
expect(first.content, 'Remind me to call Sam');
expect(first.pubkey, owner.public);
expect(first.getTagValue('h'), _Relay.dmId);
expect(first.tags, contains(equals(['p', bestie.public])));
// A sent message leaves the DM's draft as it was.
final drafts = container.read(composeDraftsProvider.notifier);
drafts.save(
key: _Relay.dmId,
channelId: _Relay.dmId,
text: 'Half a @Sam',
mentions: [ComposeDraftMention(start: 7, end: 11, pubkey: 'a' * 64)],
);
// A second quick send goes to the same DM.
final (_, again) = await siri('send', {
'text': 'And buy milk',
'bestie': bestie.public,
'scope': scope,
});
expect(again, isNull);
final messages = relay.published.where((e) => e.kind == 9).toList();
expect(messages.map((e) => e.content), [
'Remind me to call Sam',
'And buy milk',
]);
expect(messages.map((e) => e.getTagValue('h')).toSet(), {_Relay.dmId});
expect(drafts.textFor(_Relay.dmId), 'Half a @Sam');
// When Buzz can't tell whether a send landed, the text stays in the DM's
// draft, after the person's own, and Siri says to check before resending.
relay.timeOutNextMessage = true;
final (_, unsure) = await siri('send', {
'text': 'Call back',
'bestie': bestie.public,
'scope': scope,
});
expect(
unsure?.message,
"Buzz isn't sure that sent. Check your Bestie DM before trying again.",
);
final kept = drafts.draftFor(_Relay.dmId)!;
expect(kept.text, 'Half a @Sam\n\nCall back');
expect(kept.mentions, [
ComposeDraftMention(start: 7, end: 11, pubkey: 'a' * 64),
]);
// A socket that drops just before the message goes out keeps it too.
relay.dropBeforeNextMessage = true;
final (_, dropped) = await siri('send', {
'text': 'Then Sam',
'bestie': bestie.public,
'scope': scope,
});
expect(dropped?.message, contains('Check your Bestie DM'));
expect(drafts.textFor(_Relay.dmId), 'Half a @Sam\n\nCall back\n\nThen Sam');
// Leaving Home, for example on sign-out, takes the handler with it.
await tester.pumpWidget(const SizedBox());
expect(platformCalls, ['ready', 'unready']);
// Let the sent messages' local animations finish.
await tester.pump(const Duration(seconds: 10));
});
}