fix(mobile): keep undecodable emoji bytes out of shared caches

Image loads report their bytes to observers only once a frame decodes,
so the custom emoji bytes cache never holds an error body that the
native picker or reaction sheet would serve without retrying. Emoji
already saved on disk skip the picker's download slots, and a cell that
left during its decode keeps only its first frame.

Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Signed-off-by: Tom Brow <tomb@squareup.com>
This commit is contained in:
Tom Brow
2026-11-13 11:27:11 -08:00
parent af505c284e
commit 913eb4c939
7 changed files with 101 additions and 4 deletions

View File

@@ -483,6 +483,8 @@ enum NativeEmojiRemoteImageLoader {
let decoded = await Task.detached(priority: .userInitiated) {
NativeMessageImageLoader.decode(bytes, maximumPixelSize: maximumPixelSize)
}.value
// A cell that left during the decode keeps only its first frame.
try Task.checkCancellation()
guard let decoded else { throw NativeEmojiRemoteImageError.invalidImage }
return decoded
}

View File

@@ -169,9 +169,14 @@ Future<void> _presentIosEmojiPicker({
if (emojiBytes.lookup(url) case final Uint8List bytes) return bytes;
final cancel = Completer<void>();
mediaBytesCancels[id] = cancel;
// Only downloads wait for a slot; saved emoji load at once.
var admittedLoad = false;
try {
if (activeMediaLoads < _maxNativeMediaLoads) {
if (await mediaDiskCache?.contains(url) ?? false) {
// Read from disk below without a slot.
} else if (activeMediaLoads < _maxNativeMediaLoads) {
activeMediaLoads++;
admittedLoad = true;
} else {
final admitted = Completer<void>();
queuedMediaLoads.add(admitted);
@@ -180,6 +185,7 @@ Future<void> _presentIosEmojiPicker({
queuedMediaLoads.remove(admitted);
throw StateError('Media bytes load cancelled');
}
admittedLoad = true;
}
} on Object {
mediaBytesCancels.remove(id);
@@ -196,7 +202,7 @@ Future<void> _presentIosEmojiPicker({
return bytes;
} finally {
mediaBytesCancels.remove(id);
releaseMediaLoad();
if (admittedLoad) releaseMediaLoad();
}
case 'cancelMediaBytes':
final cancel = mediaBytesCancels.remove(call.arguments as int);

View File

@@ -186,6 +186,18 @@ class MediaDiskCache {
}
}
/// Whether [url] has saved bytes, from the index alone, without reading
/// them.
Future<bool> contains(String url) async {
try {
final manager = await _manager;
return await manager?.getFileFromCache(url, ignoreMemCache: true) != null;
} on Object catch (error) {
_logFailure(error);
return false;
}
}
/// [url]'s saved bytes, or null when they are not on disk.
Future<MediaDiskCacheHit?> read(String url) async {
final FileInfo? info;

View File

@@ -90,7 +90,8 @@ class MediaImageProvider extends ImageProvider<MediaImageProvider> {
final double scale;
final MediaGetAuthService auth;
/// Optional observer for bytes already fetched by the foreground image path.
/// Optional observer for bytes the foreground image path fetched and
/// decoded a frame from.
/// Excluded from equality because it is a side effect, not cache identity.
final ValueChanged<Uint8List>? onBytesLoaded;
@@ -182,6 +183,7 @@ class MediaImageProvider extends ImageProvider<MediaImageProvider> {
) {
final abandoned = Completer<void>();
_SharedFetch? fetched;
Uint8List? loadedBytes;
// The image cache listens to a pending load, so this fires mid-download
// only once a consumer evicts the entry and stops listening (see
// [abandonPendingImage]), as [MediaImage] does when it stops showing an
@@ -192,6 +194,7 @@ class MediaImageProvider extends ImageProvider<MediaImageProvider> {
decode,
abandoned.future,
onFetch: (fetch) => fetched = fetch,
onBytes: (bytes) => loadedBytes = bytes,
),
scale: key.scale,
debugLabel: url,
@@ -202,6 +205,11 @@ class MediaImageProvider extends ImageProvider<MediaImageProvider> {
onSettled: (decoded) {
fetched?.settle(decoded: decoded);
fetched = null;
// Report only bytes that decoded, so observers such as the picker's
// bytes cache never keep an error body.
final bytes = loadedBytes;
loadedBytes = null;
if (decoded && bytes != null) onBytesLoaded?.call(bytes);
},
)..addOnLastListenerRemovedCallback(() {
if (!abandoned.isCompleted) abandoned.complete();
@@ -213,6 +221,7 @@ class MediaImageProvider extends ImageProvider<MediaImageProvider> {
ImageDecoderCallback decode,
Future<void> abandoned, {
required void Function(_SharedFetch) onFetch,
required void Function(Uint8List) onBytes,
}) async {
var wasAbandoned = false;
try {
@@ -249,7 +258,7 @@ class MediaImageProvider extends ImageProvider<MediaImageProvider> {
}
// Another size kept the download going, but this load's consumer left.
if (wasAbandoned) throw StateError('Image load abandoned');
onBytesLoaded?.call(bytes);
onBytes(bytes);
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
return withBrowserFrameTiming(await decode(buffer));
} catch (_) {

View File

@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:buzz/shared/emoji/emoji_picker.dart';
import 'package:buzz/shared/emoji/recent_emoji_provider.dart';
@@ -733,6 +734,19 @@ void main() {
nsec: nostr.Keys.generate().nsec,
);
final mediaClient = _MediaClient();
final diskDirectory = (await tester.runAsync(
() => Directory.systemTemp.createTemp('emoji_picker_test'),
))!;
// The cache's own I/O and timers need the real event loop.
final diskCache = (await tester.runAsync(
() async => MediaDiskCache.open(diskDirectory),
))!;
addTearDown(
() => tester.runAsync(() async {
await diskCache.dispose();
await diskDirectory.delete(recursive: true);
}),
);
MethodCall? presentation;
final selected = <String>[];
var dismissals = 0;
@@ -754,6 +768,7 @@ void main() {
),
mediaGetAuthServiceProvider.overrideWithValue(mediaAuth),
mediaHttpClientProvider.overrideWithValue(mediaClient),
mediaDiskCacheProvider.overrideWithValue(diskCache),
],
child: MaterialApp(
theme: AppTheme.light(),
@@ -845,6 +860,20 @@ void main() {
);
await Future<void>.delayed(const Duration(milliseconds: 50));
expect(mediaClient.requests, hasLength(4));
// An emoji already saved on disk does not wait for a slot.
await diskCache.write(
'https://example.test/saved.png',
_pngBytes,
immutable: false,
);
expect(
await _sendNativeEmojiPickerCall(tester, 'mediaBytes', {
'id': 15,
'url': 'https://example.test/saved.png',
}),
_pngBytes,
);
expect(mediaClient.requests, hasLength(4));
await _sendNativeEmojiPickerCall(tester, 'cancelMediaBytes', 14);
await queued;
for (var id = 10; id < 14; id++) {

View File

@@ -419,9 +419,11 @@ void main() {
diskCache: cache,
).loadEncodedBytes(cancel: Completer<void>().future);
expect(await cache.contains(_truncatedUrl), isTrue);
await expectLater(load(), throwsA(anything));
expect(fetched, isEmpty);
await _settle();
expect(await cache.contains(_truncatedUrl), isFalse);
MediaImageProvider.debugResetCooldowns();
expect(await load(), _pngBytes);
expect(fetched, [_truncatedUrl]);

View File

@@ -284,6 +284,43 @@ void main() {
},
);
test('reports only bytes that decoded to observers', () async {
final client = http_testing.MockClient((request) async {
if (request.url.path.endsWith('broken.png')) {
return http.Response('<html>error</html>', 200);
}
// Opens a codec, then fails its first frame.
if (request.url.path.endsWith('truncated.png')) {
return http.Response.bytes(_pngBytes.sublist(0, 41), 200);
}
return http.Response.bytes(_pngBytes, 200);
});
final delivered = <String>[];
MediaImageProvider provider(String url) => MediaImageProvider(
url: url,
auth: _auth(),
client: client,
onBytesLoaded: (_) => delivered.add(url),
);
for (final name in ['broken', 'truncated']) {
expect(
await _waitError(
provider(
'https://emoji.example/$name.png',
).resolve(ImageConfiguration.empty),
),
isNotNull,
);
}
await _wait(
provider(
'https://emoji.example/ok.png',
).resolve(ImageConfiguration.empty),
);
expect(delivered, ['https://emoji.example/ok.png']);
PaintingBinding.instance.imageCache.clear();
});
test('resolves one fetch for repeated resolves of the same key', () async {
var fetches = 0;
final client = http_testing.MockClient((request) async {