Files
buzz/mobile/test/shared/widgets/preset_agent_avatar_test.dart
Tom Brow 39ffc3dcc5 fix(mobile): keep agent poster up until the iOS video draws (#9688)
On iOS, an animated agent avatar (a preset character with a transparent
video) blinks out for one to three frames right after navigation
settles. Opening a Solo chat blanks the header avatar; going back to
Messages blanks the bestie bubble.

The cause is the hand-off from the still poster to the video. While a
route animates, `PresetAgentAvatar` shows the poster; once it settles it
replaced the poster with a native `AVPlayerLayer`, which draws nothing
until its first video frame arrives. The avatar picker and the
create-agent page already covered this by passing a preloaded poster;
the DM and Solo header and the bestie bubble pass none, so they went
straight to the bare player.

Now every iOS caller gets that hand-off, using its own poster when it
passes none: the poster stays up, below the player, until playback
advances in that showing, then fades out over 160 ms. The poster sits
below the native layer rather than over it, because a Flutter overlay
above a platform view also costs a blank frame when the view first
appears. Each showing starts covered again and waits for playback to
advance from where the player actually is, so coming back to a chat from
a page above it doesn't blink either. The poster is keyed by its URL, so
when the avatar changes to another character (for example a synced
bestie change) it never shows the previous character's poster. Android
is unchanged; it already waits for a presented frame.

### Validation

Measured on an iPhone 17 Pro simulator, recording at 60 fps and checking
the avatar region frame by frame, opening a Solo chat with an animated
agent and going back:

| | Header blank on open | Bubble blank on back |
| --- | --- | --- |
| main, 3 runs | 1 frame every run | 2 to 3 frames every run |
| this PR, 3 runs | none | none |

Before (left) and after (right), slowed 4x: the Solo header on open,
then the bestie bubble on back.

<video
src="https://github.com/user-attachments/assets/4ddf16c0-bb8d-4d77-b53e-84f83ff45e98"
width="480"></video>

Added test: [iOS keeps the poster over a new player until playback
advances](2b172d1b68/mobile/test/shared/widgets/preset_agent_avatar_test.dart),
covering a first showing, a return to the route, and a change of
character while the video is showing.

### Regressions

- No extra work: the poster image was already loaded for the transition,
and the video plays exactly as before.
- During the 160 ms fade, poster and video overlap. They show the same
character, so the fade reads as a single image, as it already did in the
avatar picker.
- If the video never starts playing, the poster just stays up, which is
what callers showed before the video was ready anyway.





buzz-review-completed

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-18 19:57:44 -08:00

412 lines
15 KiB
Dart

import 'package:buzz/shared/widgets/dm_header_portrait.dart';
import 'package:buzz/shared/widgets/preset_agent_avatar.dart';
import 'package:buzz/shared/widgets/avatar_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
class _Player extends VideoPlayerPlatform {
bool playing = false;
double volume = 1;
Duration position = Duration.zero;
@override
Future<void> init() async {}
@override
Future<int?> createWithOptions(VideoCreationOptions options) async => 1;
@override
Stream<VideoEvent> videoEventsFor(int id) {
return Stream.value(
VideoEvent(
eventType: VideoEventType.initialized,
duration: const Duration(seconds: 2),
size: const Size(100, 100),
),
);
}
@override
Widget buildView(int id) => const SizedBox(key: Key('video'));
@override
Future<void> play(int id) async {
playing = true;
}
@override
Future<void> pause(int id) async {
playing = false;
}
@override
Future<void> setLooping(int id, bool looping) async {}
@override
Future<void> setVolume(int id, double value) async {
volume = value;
}
@override
Future<void> setPlaybackSpeed(int id, double speed) async {}
@override
Future<void> setMixWithOthers(bool value) async {}
@override
Future<Duration> getPosition(int id) async => position;
@override
Future<void> dispose(int id) async {}
}
void main() {
testWidgets(
'DM header plays transparent agent artwork and honors reduced motion',
(tester) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
addTearDown(() => debugDefaultTargetPlatformOverride = null);
final original = VideoPlayerPlatform.instance;
final player = _Player();
VideoPlayerPlatform.instance = player;
addTearDown(() => VideoPlayerPlatform.instance = original);
Widget surface({bool reduced = false}) => ProviderScope(
child: MaterialApp(
home: MediaQuery(
data: MediaQueryData(disableAnimations: reduced),
child: const Center(
child: DmHeaderPortrait(
imageUrl:
'https://dwwgwmfqqjotj.cloudfront.net/avatars/20260925T154625166Z/poster/gloopies/gloopies-13.png',
isAgent: true,
initial: 'A',
size: 64,
),
),
),
),
);
await tester.pumpWidget(surface());
await tester.pumpAndSettle();
expect(find.byKey(const Key('video')), findsOneWidget);
expect(player.playing, isTrue);
expect(
find.descendant(
of: find.byType(DmHeaderPortrait),
matching: find.byType(DecoratedBox),
),
findsNothing,
);
await tester.pumpWidget(surface(reduced: true));
await tester.pumpAndSettle();
expect(find.byKey(const Key('video')), findsNothing);
expect(find.byType(AvatarImageContent), findsOneWidget);
await tester.pumpWidget(const SizedBox());
debugDefaultTargetPlatformOverride = null;
},
);
testWidgets(
'preset plays silently, pauses when hidden, and respects reduced motion',
(tester) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
addTearDown(() => debugDefaultTargetPlatformOverride = null);
final original = VideoPlayerPlatform.instance;
final player = _Player();
VideoPlayerPlatform.instance = player;
addTearDown(() => VideoPlayerPlatform.instance = original);
Widget surface({
bool visible = true,
bool reduced = false,
bool preparedPoster = false,
}) => ProviderScope(
child: MaterialApp(
home: MediaQuery(
data: MediaQueryData(disableAnimations: reduced),
child: TickerMode(
enabled: visible,
child: PresetAgentAvatar(
posterPlaceholder: preparedPoster
? const SizedBox(key: Key('prepared-poster'))
: null,
imageUrl:
'https://dwwgwmfqqjotj.cloudfront.net/avatars/20260925T154625166Z/poster/gloopies/gloopies-13.png',
size: 50.4,
fallback: Text('Swiss'),
),
),
),
),
);
await tester.pumpWidget(surface());
await tester.pumpAndSettle();
expect(find.byKey(const Key('video')), findsOneWidget);
expect(player.playing, isTrue);
expect(player.volume, 0);
await tester.pumpWidget(surface(visible: false));
await tester.pump();
expect(player.playing, isFalse);
await tester.pumpWidget(surface());
await tester.pump();
expect(player.playing, isTrue);
await tester.pumpWidget(surface(preparedPoster: true));
await tester.pump();
expect(
tester.widget<AnimatedOpacity>(find.byType(AnimatedOpacity)).opacity,
1,
);
player.position = const Duration(milliseconds: 100);
await tester.pump(const Duration(milliseconds: 600));
await tester.pump();
expect(
tester.widget<AnimatedOpacity>(find.byType(AnimatedOpacity)).opacity,
0,
);
// Looping back to zero must not flash the poster again.
player.position = Duration.zero;
await tester.pump(const Duration(milliseconds: 600));
await tester.pump();
expect(
tester.widget<AnimatedOpacity>(find.byType(AnimatedOpacity)).opacity,
0,
);
final navigator = tester.state<NavigatorState>(find.byType(Navigator));
navigator.push<void>(
PageRouteBuilder<void>(
opaque: false,
transitionDuration: const Duration(milliseconds: 240),
reverseTransitionDuration: const Duration(milliseconds: 240),
pageBuilder: (_, _, _) => const SizedBox.shrink(),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 60));
expect(find.byKey(const Key('video')), findsNothing);
expect(find.byKey(const Key('prepared-poster')), findsOneWidget);
await tester.pumpAndSettle();
navigator.pop();
await tester.pumpAndSettle();
expect(find.byKey(const Key('video')), findsOneWidget);
expect(player.playing, isTrue);
await tester.pumpWidget(surface(reduced: true));
await tester.pumpAndSettle();
expect(find.byKey(const Key('video')), findsNothing);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink());
debugDefaultTargetPlatformOverride = null;
},
);
testWidgets('iOS keeps the poster over a new player until playback advances', (
tester,
) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
addTearDown(() => debugDefaultTargetPlatformOverride = null);
final original = VideoPlayerPlatform.instance;
final player = _Player();
VideoPlayerPlatform.instance = player;
addTearDown(() => VideoPlayerPlatform.instance = original);
double posterOpacity() =>
tester.widget<AnimatedOpacity>(find.byType(AnimatedOpacity)).opacity;
double videoOpacity() => tester
.widget<Opacity>(
find.ancestor(
of: find.byKey(const Key('video')),
matching: find.byType(Opacity),
),
)
.opacity;
await tester.pumpWidget(
const ProviderScope(
child: MaterialApp(
home: PresetAgentAvatar(
imageUrl:
'https://dwwgwmfqqjotj.cloudfront.net/avatars/20260925T154625166Z/poster/gloopies/gloopies-13.png',
size: 64,
fallback: Text('A'),
),
),
),
);
await tester.pumpAndSettle();
expect(find.byKey(const Key('video')), findsOneWidget);
expect(videoOpacity(), 0);
expect(posterOpacity(), 1);
player.position = const Duration(milliseconds: 100);
await tester.pump(const Duration(milliseconds: 600));
await tester.pumpAndSettle();
expect(videoOpacity(), 1);
expect(posterOpacity(), 0);
// Returning to the route mounts a new player, which starts covered.
final navigator = tester.state<NavigatorState>(find.byType(Navigator));
navigator.push<void>(
PageRouteBuilder<void>(
opaque: false,
pageBuilder: (_, _, _) => const SizedBox.shrink(),
),
);
await tester.pump();
expect(find.byKey(const Key('video')), findsNothing);
expect(posterOpacity(), 1);
// The player is past the last polled position when it comes back; the
// poster waits for playback to advance from where it actually is.
player.position = const Duration(milliseconds: 700);
await tester.pumpAndSettle();
navigator.pop();
// Step real frames: the baseline lands before the first poll does.
for (var frame = 0; frame < 60; frame++) {
await tester.pump(const Duration(milliseconds: 16));
if (find.byKey(const Key('video')).evaluate().isNotEmpty) {
expect(videoOpacity(), 0);
expect(posterOpacity(), 1);
}
}
expect(find.byKey(const Key('video')), findsOneWidget);
player.position = const Duration(milliseconds: 800);
await tester.pump(const Duration(milliseconds: 600));
await tester.pumpAndSettle();
expect(videoOpacity(), 1);
expect(posterOpacity(), 0);
// A new character covers with its own poster, never the previous one
// kept by gapless playback.
final previous = tester.state(find.byType(AvatarImageContent));
await tester.pumpWidget(
const ProviderScope(
child: MaterialApp(
home: PresetAgentAvatar(
imageUrl:
'https://dwwgwmfqqjotj.cloudfront.net/avatars/20260925T154625166Z/poster/gloopies/gloopies-14.png',
size: 64,
fallback: Text('A'),
),
),
),
);
await tester.pump();
final posters = tester
.widgetList<AvatarImageContent>(find.byType(AvatarImageContent))
.map((poster) => poster.imageUrl);
expect(posters, [endsWith('gloopies-14.png')]);
expect(
tester.state(find.byType(AvatarImageContent)),
isNot(same(previous)),
);
await tester.pumpWidget(const SizedBox.shrink());
debugDefaultTargetPlatformOverride = null;
});
testWidgets('Android uses transparent renderer and pauses offscreen', (
tester,
) async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
addTearDown(() => debugDefaultTargetPlatformOverride = null);
final messenger = tester.binding.defaultBinaryMessenger;
final playback = <bool>[];
var rejectPlayback = false;
var frameReady = false;
var frameFailed = false;
var readinessCalls = 0;
final channels = <MethodChannel>[];
messenger.setMockMethodCallHandler(SystemChannels.platform_views, (
call,
) async {
if (call.method == 'create') {
final args = call.arguments as Map;
expect(args['viewType'], 'buzz/transparent-avatar');
final channel = MethodChannel('buzz/transparent-avatar/${args['id']}');
channels.add(channel);
messenger.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'isReady') {
readinessCalls++;
return frameFailed
? 'failed'
: frameReady
? 'ready'
: 'loading';
}
if (call.method == 'setPlaying') {
if (rejectPlayback) throw PlatformException(code: 'unavailable');
playback.add(call.arguments as bool);
}
return null;
});
return 1;
}
if (call.method == 'resize') {
final args = call.arguments as Map;
return {'width': args['width'], 'height': args['height']};
}
return null;
});
addTearDown(() {
messenger.setMockMethodCallHandler(SystemChannels.platform_views, null);
for (final channel in channels) {
messenger.setMockMethodCallHandler(channel, null);
}
});
Widget surface({
bool visible = true,
bool reduced = false,
}) => ProviderScope(
child: MaterialApp(
home: MediaQuery(
data: MediaQueryData(disableAnimations: reduced),
child: TickerMode(
enabled: visible,
child: const PresetAgentAvatar(
imageUrl:
'https://dwwgwmfqqjotj.cloudfront.net/avatars/20260925T154625166Z/poster/gloopies/gloopies-13.png',
size: 50.4,
fallback: Text('Swiss'),
),
),
),
),
);
await tester.pumpWidget(surface());
await tester.pumpAndSettle();
expect(find.byType(AndroidView), findsOneWidget);
// The poster stays until Chromium has actually presented a video frame.
expect(find.byType(AvatarImageContent), findsOneWidget);
// A slow download must still become visible after the old ten-second cap.
for (var i = 0; i < 220; i++) {
await tester.pump(const Duration(milliseconds: 50));
}
frameReady = true;
await tester.pump(const Duration(milliseconds: 50));
await tester.pump();
expect(
tester.widget<AnimatedOpacity>(find.byType(AnimatedOpacity)).opacity,
0,
);
expect(playback.last, true);
await tester.pumpWidget(surface(visible: false));
await tester.pumpAndSettle();
expect(playback.last, false);
await tester.pumpWidget(surface());
await tester.pumpAndSettle();
expect(playback.last, true);
await tester.pumpWidget(surface(reduced: true));
await tester.pumpAndSettle();
expect(find.byType(AndroidView), findsNothing);
frameReady = false;
frameFailed = true;
await tester.pumpWidget(surface());
await tester.pumpAndSettle();
expect(find.byType(AndroidView), findsNothing);
expect(find.byType(AvatarImageContent), findsOneWidget);
final stoppedAt = readinessCalls;
await tester.pump(const Duration(seconds: 15));
await tester.pumpWidget(surface(visible: false));
await tester.pumpWidget(surface());
await tester.pump(const Duration(seconds: 15));
expect(readinessCalls, stoppedAt);
await tester.pumpWidget(surface(reduced: true));
await tester.pumpAndSettle();
frameFailed = false;
rejectPlayback = true;
await tester.pumpWidget(surface());
await tester.pumpAndSettle();
expect(find.byType(AndroidView), findsNothing);
expect(find.byType(AvatarImageContent), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink());
debugDefaultTargetPlatformOverride = null;
});
}