Files
buzz/mobile/test/features/pairing/pairing_qr_scanner_test.dart
Daniel Rouleau 14037e3278 fix(mobile): show progress after pairing QR scans (#9009)
## Summary

After a pairing QR scan, the app shows connection progress until code
entry or a connection error. A WebSocket handshake that remains pending
stops after ten seconds. Cancel is available until storage starts. It
resets pairing and restores the entry form. Pasted codes remain
available after an error or cancellation. Back navigation stays blocked
during identity transfer and storage. Cancel on Send identity to desktop
returns to Settings, so another attempt starts through the authorization
step.

### Related issue

Related to [#9001](https://github.com/block/buzz/pull/9001), which
covers organization sign-in after identity transfer. This change covers
the earlier connection stage.

### Testing

A simulator build with PR #9001 completes identity transfer and saves
the community. The community chooser still blocks organization sign-in.
[PR #9028](https://github.com/block/buzz/pull/9028) covers that step.
Physical iPhone testing and successful real-relay checks in light and
dark mode remain pending. On a build with this change, scan a desktop
pairing QR code. Check that progress appears, Cancel returns to the
entry form, and a fresh attempt reaches code entry. Paste a pairing
code, cancel during connection, and check that the form keeps the code.
Test a failed connection and retry. In Settings, open Send identity to
desktop, start a recovery connection, and cancel. Check that Settings
appears and another attempt asks for authorization. Camera recognition
speed and the reported intermittent phone network failure remain
unverified.

Generated with Codex

---------

Signed-off-by: Daniel Rouleau <drouleau@squareup.com>
Co-authored-by: Sol <c35e7cc95f6fdbfb7e861dccc02bdca567b6d6b20f16b5115c3c6ae082bbeede@buzz.block.builderlab.xyz>
2026-11-03 19:12:57 -08:00

717 lines
24 KiB
Dart

import 'dart:io';
import 'package:buzz/features/pairing/pairing_provider.dart';
import '../../helpers/controllable_pairing_socket.dart';
import 'dart:async';
import 'package:buzz/features/pairing/pairing_qr_scanner.dart';
import 'package:buzz/features/pairing/pairing_page.dart';
import '../../helpers/widget_helpers.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
const _qrScannerPlatformChannel = MethodChannel('buzz/qr_scanner');
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final defaultScannerPlatform = MobileScannerPlatform.instance;
late _FakeMobileScannerPlatform fakeScannerPlatform;
setUp(() {
fakeScannerPlatform = _FakeMobileScannerPlatform();
MobileScannerPlatform.instance = fakeScannerPlatform;
});
tearDown(() async {
debugDefaultTargetPlatformOverride = null;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_qrScannerPlatformChannel, null);
await fakeScannerPlatform.dispose();
MobileScannerPlatform.instance = defaultScannerPlatform;
});
for (final (paste, cancel) in [
(false, false),
(true, false),
(false, true),
(true, true),
]) {
testWidgets('pairing entry paste=$paste cancel=$cancel permits retry', (
tester,
) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
_qrScannerPlatformChannel,
(call) async =>
call.method == 'usesDynamicIslandQrScannerPortal' ? true : null,
);
final readiness = Completer<void>();
final notifier = PairingNotifier(
socketFactory:
({
required wsUrl,
required ephemeralPrivkey,
required onMessage,
required onDisconnected,
}) => _PendingPairingSocket(
readiness.future,
ephemeralPrivkey: ephemeralPrivkey,
onMessage: onMessage,
onDisconnected: onDisconnected,
),
);
await tester.pumpWidget(
WidgetHelpers.testable(
disableAnimations: true,
overrides: [pairingProvider.overrideWith(() => notifier)],
child: PairingPage(
addingCommunity: paste,
existingUser: paste,
connectionLanding: true,
showConnectionOptions: false,
),
),
);
const code =
'nostrpair://79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'
'?secret=abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789'
'&relay=wss%3A%2F%2Fpairing.example&v=1';
if (paste) {
await tester.enterText(
find.byKey(const Key('community-pairing-input')),
code,
);
await tester.tap(find.text('Connect'));
} else {
await tester.tap(find.text('Scan a QR code'));
await tester.pump();
await tester.pump();
fakeScannerPlatform._barcodes.add(
BarcodeCapture(barcodes: [Barcode(rawValue: code)]),
);
}
await tester.pump();
await tester.pump();
await tester.pump();
expect(
find.byKey(const Key('pairing-community-loading')),
findsOneWidget,
);
expect(find.text('Scan a QR code'), findsNothing);
if (cancel) {
await tester.tap(find.text('Cancel'));
await tester.pump();
expect(
find.byKey(const Key('pairing-community-loading')),
findsNothing,
);
}
readiness.completeError(const SocketException('Network is unreachable'));
await tester.pump();
await tester.pump();
expect(
find.textContaining('Could not reach the pairing relay'),
cancel ? findsNothing : findsOneWidget,
);
if (paste) {
expect(
tester
.widget<TextField>(
find.byKey(const Key('community-pairing-input')),
)
.controller!
.text,
code,
);
expect(
tester
.widget<FilledButton>(
find.widgetWithText(FilledButton, 'Connect'),
)
.onPressed,
isNotNull,
);
} else {
expect(find.text('Scan a QR code'), findsOneWidget);
}
debugDefaultTargetPlatformOverride = null;
});
}
group('DynamicIslandQrScannerGeometry', () {
const viewport = Size(393, 852);
const geometry = DynamicIslandQrScannerGeometry(
viewport: viewport,
safeAreaTop: 59,
);
test('starts at the physical Dynamic Island frame', () {
expect(geometry.collapsedFrame, const Rect.fromLTWH(136.5, 11, 120, 36));
});
test('keeps the top edge fixed while the camera grows down', () {
final start = geometry.frameAt(0);
final middle = geometry.frameAt(0.5);
final end = geometry.frameAt(1);
expect(middle.top, start.top);
expect(end.top, start.top);
expect(middle.bottom, greaterThan(start.bottom));
expect(end.bottom, greaterThan(middle.bottom));
expect(end, const Rect.fromLTWH(15, 11, 363, 363));
});
test('delays the camera until the portal has left the island', () {
expect(geometry.scannerOpacityAt(0.18), 0);
expect(geometry.scannerOpacityAt(0.5), greaterThan(0));
expect(geometry.scannerOpacityAt(1), 1);
});
});
group('usesDynamicIslandQrScannerPortal', () {
test('asks the native bridge on iOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_qrScannerPlatformChannel, (call) async {
expect(call.method, 'usesDynamicIslandQrScannerPortal');
return true;
});
expect(await usesDynamicIslandQrScannerPortal(), isTrue);
});
test('uses the fallback without asking native code on Android', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
var nativeCalls = 0;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_qrScannerPlatformChannel, (call) async {
nativeCalls += 1;
return true;
});
expect(await usesDynamicIslandQrScannerPortal(), isFalse);
expect(nativeCalls, 0);
});
});
testWidgets('fallback reveals the camera behind the current app surface', (
tester,
) async {
await tester.binding.setSurfaceSize(const Size(375, 667));
addTearDown(() => tester.binding.setSurfaceSize(null));
var scannerClosed = false;
await tester.pumpWidget(
MaterialApp(
home: FallbackPairingQrScanner(
appSurface: const ColoredBox(
color: Colors.white,
child: Center(child: Text('Current app surface')),
),
onClosed: (_) {
scannerClosed = true;
},
),
),
);
final sheet = find.byKey(const ValueKey('fallback-qr-scanner-app-sheet'));
expect(tester.getRect(sheet).top, 0);
expect(find.text('Current app surface'), findsOneWidget);
await tester.pump(const Duration(milliseconds: 420));
expect(tester.getRect(sheet).top, closeTo(555, 0.1));
await tester.tapAt(const Offset(187.5, 100));
await tester.pump();
expect(scannerClosed, isFalse);
await tester.pump(const Duration(milliseconds: 320));
await tester.pumpAndSettle();
expect(scannerClosed, isTrue);
expect(tester.getRect(sheet).top, 0);
});
testWidgets(
'portal route opens from the island and an outside tap reverses it closed',
(tester) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_qrScannerPlatformChannel, (call) async {
return switch (call.method) {
'usesDynamicIslandQrScannerPortal' => true,
'setDynamicIslandScannerStatusBarHidden' => null,
_ => null,
};
});
await tester.binding.setSurfaceSize(const Size(393, 852));
addTearDown(() => tester.binding.setSurfaceSize(null));
final cameraStart = Completer<void>();
fakeScannerPlatform.startGate = cameraStart.future;
var scannerClosed = false;
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: const MediaQueryData(
size: Size(393, 852),
viewPadding: EdgeInsets.only(top: 59),
),
child: Builder(
builder: (context) => TextButton(
onPressed: () async {
await showDynamicIslandPairingQrScanner(context);
scannerClosed = true;
},
child: const Text('Open scanner'),
),
),
),
),
);
await tester.tap(find.text('Open scanner'));
await tester.pump();
final portal = find.byKey(
const ValueKey('dynamic-island-qr-scanner-portal'),
);
expect(tester.getRect(portal), const Rect.fromLTWH(136.5, 11, 120, 36));
final prompt = find
.ancestor(
of: find.text('Scan a QR code'),
matching: find.byType(Opacity),
)
.first;
final camera = find
.ancestor(
of: find.byType(MobileScanner),
matching: find.byType(Opacity),
)
.first;
expect(tester.widget<Opacity>(prompt).opacity, 0);
expect(find.byType(MobileScanner), findsOneWidget);
await tester.pump();
expect(fakeScannerPlatform.startCalls, 1);
expect(
tester.widget<ClipRSuperellipse>(portal).borderRadius,
BorderRadius.circular(18),
);
expect(
tester.widget<ClipRSuperellipse>(portal).clipBehavior,
Clip.antiAlias,
);
await tester.pump(const Duration(milliseconds: 12));
final firstOpeningFrame = tester.getRect(portal);
expect(firstOpeningFrame.height, inExclusiveRange(36, 363));
await tester.pump(const Duration(milliseconds: 218));
expect(
tester.widget<Opacity>(prompt).opacity,
tester.widget<Opacity>(camera).opacity,
);
expect(tester.widget<Opacity>(prompt).opacity, inExclusiveRange(0, 1));
expect(
tester.getRect(portal).height,
greaterThan(firstOpeningFrame.height),
);
final openingRadius =
(tester.widget<ClipRSuperellipse>(portal).borderRadius
as BorderRadius)
.topLeft
.x;
expect(openingRadius, inExclusiveRange(18, 40));
await tester.pumpAndSettle();
final readyFade = find.byKey(const ValueKey('qr-camera-ready-fade'));
final previewFade = find
.descendant(of: readyFade, matching: find.byType(FadeTransition))
.first;
expect(tester.widget<FadeTransition>(previewFade).opacity.value, 0);
cameraStart.complete();
await tester.pump();
await tester.pump();
await tester.pump(const Duration(milliseconds: 60));
expect(
tester.widget<FadeTransition>(previewFade).opacity.value,
inExclusiveRange(0, 1),
);
await tester.pumpAndSettle();
expect(tester.widget<FadeTransition>(previewFade).opacity.value, 1);
expect(
tester.widget<ClipRSuperellipse>(portal).borderRadius,
BorderRadius.circular(40),
);
expect(tester.getRect(portal).top, 11);
expect(
find.byKey(const ValueKey('dynamic-island-qr-scanner-close')),
findsNothing,
);
await tester.tapAt(const Offset(196.5, 700));
await tester.pump();
expect(scannerClosed, isFalse);
expect(find.byType(MobileScanner), findsOneWidget);
await tester.pump(const Duration(milliseconds: 100));
final earlyClosingHeight = tester.getRect(portal).height;
expect(earlyClosingHeight, lessThan(280));
expect(find.byType(MobileScanner), findsOneWidget);
await tester.pump(const Duration(milliseconds: 200));
final lateClosingHeight = tester.getRect(portal).height;
// The camera is transparent here, but must not shut down mid-collapse.
expect(find.byType(MobileScanner), findsOneWidget);
expect(
tester
.widget<Opacity>(
find
.ancestor(
of: find.byType(MobileScanner),
matching: find.byType(Opacity),
)
.first,
)
.opacity,
0,
);
expect(fakeScannerPlatform.stopCalls, 0);
expect(fakeScannerPlatform._isDisposed, isFalse);
expect(lateClosingHeight, lessThan(earlyClosingHeight));
expect(lateClosingHeight, greaterThan(36));
// The final approach is slower than the initial collapse, not an impact.
expect(lateClosingHeight - 36, lessThan((363 - earlyClosingHeight) / 4));
final closingRadius =
(tester.widget<ClipRSuperellipse>(portal).borderRadius
as BorderRadius)
.topLeft
.x;
expect(closingRadius, inExclusiveRange(18, 40));
await tester.pump(const Duration(milliseconds: 170));
await tester.pumpAndSettle();
expect(scannerClosed, isTrue);
expect(portal, findsNothing);
expect(fakeScannerPlatform._isDisposed, isTrue);
debugDefaultTargetPlatformOverride = null;
},
);
testWidgets('welcome and Add follow the scanner spring and return on close', (
tester,
) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_qrScannerPlatformChannel, (call) async {
return call.method == 'usesDynamicIslandQrScannerPortal'
? true
: null;
});
await tester.binding.setSurfaceSize(const Size(393, 852));
addTearDown(() => tester.binding.setSurfaceSize(null));
for (final (reduced, adding) in [
(false, false),
(true, false),
(false, true),
(true, true),
]) {
await tester.pumpWidget(
WidgetHelpers.testable(
disableAnimations: reduced,
child: PairingPage(
addingCommunity: adding,
connectionLanding: true,
showConnectionOptions: false,
),
),
);
await tester.pump();
final opacity = find.byKey(const Key('scanner-welcome-opacity'));
final scale = find.byKey(const Key('scanner-welcome-scale'));
void expectBeesMatchWelcome() {
if (adding) return;
expect(
tester
.widget<Opacity>(find.byKey(const Key('scanner-bees-opacity')))
.opacity,
tester.widget<Opacity>(opacity).opacity,
);
expect(
tester
.widget<Transform>(find.byKey(const Key('scanner-bees-scale')))
.transform
.storage[0],
tester.widget<Transform>(scale).transform.storage[0],
);
}
// The welcome swarm animates continuously. Wait for the scanner's
// observable transition endpoint rather than global frame idleness.
Future<void> waitForOpacity(double target) async {
for (
var frame = 0;
frame < 120 &&
(tester.widget<Opacity>(opacity).opacity != target ||
(target == 1 &&
find
.byKey(
const ValueKey('dynamic-island-qr-scanner-portal'),
)
.evaluate()
.isNotEmpty));
frame++
) {
await tester.pump(const Duration(milliseconds: 16));
}
expect(tester.widget<Opacity>(opacity).opacity, target);
}
expect(tester.widget<Opacity>(opacity).opacity, 1);
if (adding) {
// Only foreground controls transition; the opaque page stays fixed.
expect(
find.descendant(of: opacity, matching: find.byType(Scaffold)),
findsNothing,
);
expect(
find.ancestor(of: opacity, matching: find.byType(Scaffold)),
findsWidgets,
);
}
await tester.tap(find.text('Scan a QR code').hitTestable());
await tester.pump();
// Opening must begin without waiting for the welcome double-tap timeout.
expect(
find.byKey(const ValueKey('dynamic-island-qr-scanner-portal')),
findsOneWidget,
);
await tester.pump(const Duration(milliseconds: 100));
if (!reduced) {
final portal = find.byKey(
const ValueKey('dynamic-island-qr-scanner-portal'),
);
final progress = (tester.getSize(portal).height - 36) / (363 - 36);
expect(
tester.widget<Opacity>(opacity).opacity,
closeTo(1 - progress, 0.001),
);
expect(
tester.widget<Transform>(scale).transform.storage[0],
closeTo(1 - 0.04 * progress, 0.001),
);
}
expectBeesMatchWelcome();
await waitForOpacity(0);
expectBeesMatchWelcome();
expect(tester.widget<Opacity>(opacity).opacity, 0);
expect(
tester.widget<Transform>(scale).transform.storage[0],
closeTo(reduced ? 1 : 0.96, 0.001),
);
expect(
find
.ancestor(
of: find.text('Scan a QR code'),
matching: find.byType(FilledButton),
)
.hitTestable(),
findsNothing,
);
await tester.tapAt(const Offset(196.5, 700));
await tester.pump();
await waitForOpacity(1);
expectBeesMatchWelcome();
expect(tester.widget<Opacity>(opacity).opacity, 1);
expect(tester.widget<Transform>(scale).transform.storage[0], 1);
expect(
find
.ancestor(
of: find.text('Scan a QR code'),
matching: find.byType(FilledButton),
)
.hitTestable(),
findsOneWidget,
);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpAndSettle();
}
debugDefaultTargetPlatformOverride = null;
});
testWidgets(
'an early dismissal keeps its frame and settles back into the island',
(tester) async {
await tester.binding.setSurfaceSize(const Size(393, 852));
addTearDown(() => tester.binding.setSurfaceSize(null));
var closeCount = 0;
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => TextButton(
onPressed: () async {
await showDynamicIslandPairingQrScanner(context);
closeCount++;
},
child: const Text('Open scanner'),
),
),
),
);
await tester.tap(find.text('Open scanner'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 72));
final portal = find.byKey(
const ValueKey('dynamic-island-qr-scanner-portal'),
);
final beforeLastOpeningFrame = tester.getRect(portal);
await tester.pump(const Duration(milliseconds: 8));
final beforeDismissal = tester.getRect(portal);
await tester.tapAt(const Offset(196.5, 700));
await tester.pump();
expect(
tester.getRect(portal),
rectMoreOrLessEquals(beforeDismissal, epsilon: 0.00001),
);
// Preserve the outgoing velocity briefly instead of abruptly flipping it.
await tester.pump(const Duration(milliseconds: 8));
final afterDismissal = tester.getRect(portal);
expect(afterDismissal.height, greaterThan(beforeDismissal.height));
// Reversing decelerates the outgoing motion over an equal frame interval.
expect(
afterDismissal.height - beforeDismissal.height,
lessThan(beforeDismissal.height - beforeLastOpeningFrame.height),
);
await tester.tapAt(const Offset(196.5, 700));
await tester.pumpAndSettle();
expect(closeCount, 1);
expect(portal, findsNothing);
expect(find.text('Open scanner'), findsOneWidget);
expect(tester.takeException(), isNull);
},
);
testWidgets('tapping the scanner closes it without a separate control', (
tester,
) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_qrScannerPlatformChannel, (call) async {
return switch (call.method) {
'usesDynamicIslandQrScannerPortal' => true,
'setDynamicIslandScannerStatusBarHidden' => null,
_ => null,
};
});
await tester.binding.setSurfaceSize(const Size(393, 852));
addTearDown(() => tester.binding.setSurfaceSize(null));
var scannerClosed = false;
await tester.pumpWidget(
MaterialApp(
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context).copyWith(disableAnimations: true),
child: child!,
),
home: Builder(
builder: (context) => TextButton(
onPressed: () async {
await showDynamicIslandPairingQrScanner(context);
scannerClosed = true;
},
child: const Text('Open scanner'),
),
),
),
);
await tester.tap(find.text('Open scanner'));
await tester.pump();
final portal = find.byKey(
const ValueKey('dynamic-island-qr-scanner-portal'),
);
expect(tester.getRect(portal), const Rect.fromLTWH(15, 11, 363, 363));
expect(
tester.widget<ClipRSuperellipse>(portal).borderRadius,
BorderRadius.circular(40),
);
await tester.tapAt(tester.getCenter(portal));
await tester.pump();
await tester.pumpAndSettle();
expect(scannerClosed, isTrue);
expect(portal, findsNothing);
debugDefaultTargetPlatformOverride = null;
});
}
class _FakeMobileScannerPlatform extends MobileScannerPlatform {
final _barcodes = StreamController<BarcodeCapture?>.broadcast();
var _isDisposed = false;
var stopCalls = 0;
var startCalls = 0;
Future<void>? startGate;
@override
Stream<BarcodeCapture?> get barcodesStream => _barcodes.stream;
@override
Stream<TorchState> get torchStateStream =>
Stream.value(TorchState.unavailable);
@override
Stream<double> get zoomScaleStateStream => Stream.value(1);
@override
Future<MobileScannerViewAttributes> start(StartOptions startOptions) async {
startCalls++;
await startGate;
return const MobileScannerViewAttributes(
cameraDirection: CameraFacing.back,
currentTorchMode: TorchState.unavailable,
size: Size(200, 200),
numberOfCameras: 1,
);
}
@override
Widget buildCameraView() => const SizedBox.expand();
@override
Future<void> stop() async {
stopCalls++;
}
@override
Future<void> dispose() async {
if (_isDisposed) {
return;
}
_isDisposed = true;
await _barcodes.close();
}
}
class _PendingPairingSocket extends ControllablePairingSocket {
_PendingPairingSocket(
this.readiness, {
required super.ephemeralPrivkey,
required super.onMessage,
required super.onDisconnected,
});
final Future<void> readiness;
@override
Future<void> connect() async {
await readiness;
await super.connect();
}
}