Author SHA1 Message Date
Codex aab2bc0cee perf(tabs): release stale image and tab state
Pixel 10 APK / build (push) Successful in 37m12s
2026-08-10 17:59:50 +02:00
Codex 03227320f4 perf(android): move thumbnail encoding off UI path 2026-08-10 17:59:42 +02:00
13 changed files with 305 additions and 39 deletions
+7
View File
@@ -118,6 +118,13 @@ jobs:
dart pub global activate melos 7.8.1
melos bootstrap
- name: Test Pixel 10 performance regressions
working-directory: apps/weblibre
run: >-
flutter test --no-pub
test/features/geckoview/utils/image_helper_test.dart
test/features/geckoview/domain/providers/tab_detail_state_test.dart
- name: Generate bundled assets
run: |
melos run update-assets --no-select
@@ -54,6 +54,14 @@ class TabProgressStates extends _$TabProgressStates {
state = {...state}..[tabId] = progress;
}
void removeAll(Set<String> tabIds) {
if (!state.keys.any(tabIds.contains)) {
return;
}
state = {...state}..removeWhere((tabId, _) => tabIds.contains(tabId));
}
}
@Riverpod()
@@ -88,6 +96,17 @@ class TabThumbnails extends _$TabThumbnails {
state = {...state}..[tabId] = thumbnail;
}
void removeAll(Set<String> tabIds) {
if (!state.keys.any(tabIds.contains)) {
return;
}
// EquatableImage owns its ui.Image through a finalizer. Dropping the map
// reference is safer than disposing it here because an outgoing tab-preview
// frame may still hold the same wrapper briefly.
state = {...state}..removeWhere((tabId, _) => tabIds.contains(tabId));
}
}
@Riverpod()
@@ -112,6 +131,14 @@ class TabHistoryStates extends _$TabHistoryStates {
state = {...state}..[tabId] = history;
}
void removeAll(Set<String> tabIds) {
if (!state.keys.any(tabIds.contains)) {
return;
}
state = {...state}..removeWhere((tabId, _) => tabIds.contains(tabId));
}
}
@Riverpod()
@@ -142,6 +169,14 @@ class TabFindResultStates extends _$TabFindResultStates {
FindResultState resultFor(String tabId) =>
state[tabId] ?? FindResultState.$default();
void removeAll(Set<String> tabIds) {
if (!state.keys.any(tabIds.contains)) {
return;
}
state = {...state}..removeWhere((tabId, _) => tabIds.contains(tabId));
}
}
@Riverpod()
@@ -170,6 +205,14 @@ class TabTranslationStates extends _$TabTranslationStates {
state = {...state}..[tabId] = translation;
}
void removeAll(Set<String> tabIds) {
if (!state.keys.any(tabIds.contains)) {
return;
}
state = {...state}..removeWhere((tabId, _) => tabIds.contains(tabId));
}
}
@Riverpod()
@@ -36,6 +36,7 @@ import 'package:weblibre/features/geckoview/domain/entities/states/translation.d
import 'package:weblibre/features/geckoview/domain/providers.dart';
import 'package:weblibre/features/geckoview/domain/providers/selected_tab.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_detail_state.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_list.dart';
import 'package:weblibre/features/geckoview/features/find_in_page/domain/repositories/find_in_page.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/isolation_context.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
@@ -75,6 +76,14 @@ class TabStates extends _$TabStates {
state = {...state}..[tabId] = next;
}
void _removeAll(Set<String> tabIds) {
if (!state.keys.any(tabIds.contains)) {
return;
}
state = {...state}..removeWhere((tabId, _) => tabIds.contains(tabId));
}
Future<void> _onTabContentStateChange(TabContentState contentState) async {
final current = await patchedState(contentState.id);
@@ -187,6 +196,9 @@ class TabStates extends _$TabStates {
bytes,
targetWidth: thumbnailDecodeWidth,
allowUpscaling: false,
// Periodic screenshots are almost always unique. Caching each decode
// retained up to 100 obsolete GPU images in the global icon LRU.
cacheResult: false,
),
);
@@ -415,6 +427,29 @@ class TabStates extends _$TabStates {
},
);
ref.listen(tabListProvider, (previous, next) {
if (previous == null) {
// The first list can be a partial restore snapshot. There is no reliable
// removal signal until Gecko has emitted at least two snapshots.
return;
}
final activeTabIds = next.value.toSet();
final removedTabIds = previous.value
.where((tabId) => !activeTabIds.contains(tabId))
.toSet();
if (removedTabIds.isEmpty) {
return;
}
_removeAll(removedTabIds);
ref.read(tabProgressStatesProvider.notifier).removeAll(removedTabIds);
ref.read(tabThumbnailsProvider.notifier).removeAll(removedTabIds);
ref.read(tabHistoryStatesProvider.notifier).removeAll(removedTabIds);
ref.read(tabFindResultStatesProvider.notifier).removeAll(removedTabIds);
ref.read(tabTranslationStatesProvider.notifier).removeAll(removedTabIds);
});
ref.onDispose(() async {
for (final sub in subscriptions) {
await sub.cancel();
@@ -32,15 +32,18 @@ import 'package:weblibre/extensions/uri.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/tab.dart';
import 'package:weblibre/features/geckoview/domain/entities/tab_container_selection.dart';
import 'package:weblibre/features/geckoview/domain/providers.dart';
import 'package:weblibre/features/geckoview/domain/providers/desktop_mode.dart';
import 'package:weblibre/features/geckoview/domain/providers/pending_tab_selection.dart';
import 'package:weblibre/features/geckoview/domain/providers/restore_complete.dart';
import 'package:weblibre/features/geckoview/domain/providers/selected_tab.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_detail_state.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_list.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_session.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
import 'package:weblibre/features/geckoview/features/browser/domain/controllers/home_target_controller.dart';
import 'package:weblibre/features/geckoview/features/browser/domain/providers.dart';
import 'package:weblibre/features/geckoview/features/browser/domain/services/browser_data.dart';
import 'package:weblibre/features/geckoview/features/find_in_page/domain/repositories/find_in_page.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/database/database.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/isolation_context.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
@@ -1211,6 +1214,21 @@ class TabRepository extends _$TabRepository {
ref.listen(
tabListProvider,
(previous, next) async {
final activeTabIds = next.value.toSet();
final removedTabIds = previous?.value
.where((tabId) => !activeTabIds.contains(tabId))
.toSet();
if (removedTabIds != null) {
for (final tabId in removedTabIds) {
// These families are keepAlive so tab-specific state survives while
// a tab is merely in the background. Once Gecko confirms removal,
// keeping their services and listeners serves no purpose.
ref.invalidate(tabSessionProvider(tabId: tabId));
ref.invalidate(desktopModeProvider(tabId));
ref.invalidate(findInPageRepositoryProvider(tabId));
}
}
if (_suppressNextReclose) {
_suppressNextReclose = false;
// Drop tombstones for the tabs that just came back via undo so
@@ -1000,6 +1000,20 @@ class BrowserScreen extends HookConsumerWidget {
final pendingProxyLoadErrors = useRef(<String, _PendingProxyLoadError>{});
final selectedTabIdForProxyPrompt = ref.watch(selectedTabProvider);
ref.listen(tabListProvider, (previous, next) {
if (previous == null) return;
final activeTabIds = next.value.toSet();
for (final tabId in previous.value.where(
(tabId) => !activeTabIds.contains(tabId),
)) {
// UI-scoped families intentionally survive while a tab is backgrounded,
// but must not retain listeners and text state after it is closed.
ref.invalidate(toolbarVisibilityControllerProvider(tabId));
ref.invalidate(findInPageControllerProvider(tabId));
}
});
Future<void> handleProxyLoadError({
required String tabId,
required String? contextId,
@@ -111,8 +111,16 @@ class _BrowserViewState extends ConsumerState<BrowserView>
static const _pointerThrottleInterval = Duration(milliseconds: 32);
DateTime _lastPointerEvent = DateTime(0);
Offset _accumulatedDelta = Offset.zero;
bool _screenshotCaptureInFlight = false;
Future<void> _timerTick(Timer timer) async {
// Timer.periodic does not await async callbacks. A slow Gecko capture used
// to overlap the next tick, multiplying GPU readbacks, bitmap encoders and
// thumbnail events exactly while the device was already under load.
if (_screenshotCaptureInFlight) {
return;
}
// Skip the (expensive) Gecko render-to-bitmap while a full-cover route
// (settings, tab tray, search, …) occludes the browser. The screenshot
// would force an off-screen render the user can't see and competes for the
@@ -133,15 +141,17 @@ class _BrowserViewState extends ConsumerState<BrowserView>
return;
}
_screenshotCaptureInFlight = true;
try {
await ref
.read(selectedTabSessionProvider)
.requestScreenshot(requireImageResult: false)
.onError((error, stackTrace) {
.requestScreenshot(requireImageResult: false);
} catch (error, stackTrace) {
logger.e(error, stackTrace: stackTrace);
timer.cancel();
return null;
});
} finally {
_screenshotCaptureInFlight = false;
}
}
@override
@@ -27,6 +27,7 @@ import 'package:weblibre/core/logger.dart';
import 'package:weblibre/extensions/uri.dart';
import 'package:weblibre/features/geckoview/domain/providers.dart';
import 'package:weblibre/features/geckoview/domain/providers/selected_tab.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_list.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
import 'package:weblibre/features/geckoview/features/pwa/domain/pwa_installability.dart';
import 'package:weblibre/features/web_search/domain/controllers/sandbox_capture_controller.dart';
@@ -66,6 +67,21 @@ class PwaManifestState extends _$PwaManifestState {
},
);
ref.listen(tabListProvider, (previous, next) {
if (previous == null) return;
final activeTabIds = next.value.toSet();
final removedTabIds = previous.value
.where((tabId) => !activeTabIds.contains(tabId))
.toSet();
if (!removedTabIds.any(state.containsKey)) {
return;
}
state = {...state}
..removeWhere((tabId, _) => removedTabIds.contains(tabId));
});
return {};
}
}
@@ -42,6 +42,7 @@ Future<EquatableImage?> tryDecodeImage(
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true,
bool cacheResult = true,
}) async {
// The decode options are part of the identity of the result, not just of the
// request: the same bytes decoded at a thumbnail's target width and at an
@@ -55,12 +56,14 @@ Future<EquatableImage?> tryDecodeImage(
allowUpscaling: allowUpscaling,
);
if (cacheResult) {
final cached = _cache.get(identity);
if (cached?.value != null) {
return cached;
} else if (cached != null) {
_cache.remove(identity);
}
}
try {
final codec = await instantiateImageCodec(
@@ -74,7 +77,9 @@ Future<EquatableImage?> tryDecodeImage(
final image = EquatableImage(frameInfo.image, identity: identity);
if (image.value != null && image.value!.width > 0) {
if (cacheResult) {
_cache.set(identity, image);
}
return image;
}
} catch (e, s) {
@@ -87,7 +92,9 @@ Future<EquatableImage?> tryDecodeImage(
targetHeight: targetHeight,
);
if (svgImage != null) {
if (cacheResult) {
_cache.set(identity, svgImage);
}
return svgImage;
}
} catch (svgError, svgStackTrace) {
+1 -1
View File
@@ -2,7 +2,7 @@ name: weblibre
description: "The Privacy-Focused & AI-Powered Research Browser"
publish_to: 'none'
resolution: workspace
version: 0.30.0-alpha-3+40
version: 0.30.0-alpha-3+41
environment:
sdk: '>=3.8.0 <4.0.0'
@@ -0,0 +1,34 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:riverpod/riverpod.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_detail_state.dart';
void main() {
test('closed tab progress is pruned without touching active tabs', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final notifier = container.read(tabProgressStatesProvider.notifier);
notifier.update('closed-tab', 80);
notifier.update('active-tab', 40);
notifier.removeAll({'closed-tab', 'unknown-tab'});
expect(container.read(tabProgressStatesProvider), {'active-tab': 40});
});
test('pruning unrelated ids does not publish a new map', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final notifier = container.read(tabProgressStatesProvider.notifier);
notifier.update('active-tab', 40);
final before = container.read(tabProgressStatesProvider);
notifier.removeAll({'unknown-tab'});
expect(
identical(container.read(tabProgressStatesProvider), before),
isTrue,
);
});
}
@@ -75,6 +75,27 @@ void main() {
});
});
testWidgets('tryDecodeImage can bypass the global image cache', (
tester,
) async {
await tester.runAsync(() async {
clearImageCache();
final svgBytes = Uint8List.fromList(utf8.encode(_svgIcon));
final first = await tryDecodeImage(svgBytes, cacheResult: false);
final second = await tryDecodeImage(svgBytes, cacheResult: false);
expect(first, isNotNull);
expect(second, isNotNull);
expect(first, equals(second));
expect(identical(first, second), isFalse);
// These are deliberately distinct uncached image resources.
first!.dispose();
second!.dispose();
});
});
test('ImageIdentity compares structurally, not by a folded hash', () {
const a = (
digest: 0x0123456789ABCDEF,
@@ -9,32 +9,42 @@ package eu.weblibre.flutter_mozilla_components.ext
import android.graphics.Bitmap
import android.os.Build
import java.io.ByteArrayOutputStream
import kotlin.math.roundToInt
fun Bitmap.resize(maxWidth: Int, maxHeight: Int): Bitmap {
var width = this.width
var height = this.height
val aspectRatio: Float = width.toFloat() / height.toFloat()
if (width > height) {
width = maxWidth
height = (width / aspectRatio).toInt()
} else {
height = maxHeight
width = (height * aspectRatio).toInt()
require(maxWidth > 0 && maxHeight > 0) {
"Bitmap bounds must be positive"
}
return Bitmap.createScaledBitmap(this, width, height, true)
if (width <= maxWidth && height <= maxHeight) {
return this
}
val scale = minOf(
maxWidth.toFloat() / width.toFloat(),
maxHeight.toFloat() / height.toFloat(),
)
val targetWidth = (width * scale).roundToInt().coerceAtLeast(1)
val targetHeight = (height * scale).roundToInt().coerceAtLeast(1)
return Bitmap.createScaledBitmap(this, targetWidth, targetHeight, true)
}
fun Bitmap.toWebPBytes(): ByteArray {
fun Bitmap.toWebPBytes(
lossless: Boolean = true,
quality: Int = 100,
): ByteArray {
val stream = ByteArrayOutputStream()
val compressFormat = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (lossless) {
Bitmap.CompressFormat.WEBP_LOSSLESS
} else {
Bitmap.CompressFormat.WEBP_LOSSY
}
} else {
@Suppress("DEPRECATION")
Bitmap.CompressFormat.WEBP
}
compress(compressFormat, 100, stream)
compress(compressFormat, quality.coerceIn(0, 100), stream)
return stream.toByteArray()
}
@@ -19,6 +19,15 @@ import eu.weblibre.flutter_mozilla_components.pigeons.ImageSrcHitResult
import eu.weblibre.flutter_mozilla_components.pigeons.PhoneHitResult
import eu.weblibre.flutter_mozilla_components.pigeons.UnknownHitResult
import eu.weblibre.flutter_mozilla_components.pigeons.VideoHitResult
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import mozilla.components.browser.state.action.BrowserAction
import mozilla.components.browser.state.action.ContentAction
import mozilla.components.browser.state.action.LastAccessAction
@@ -45,6 +54,53 @@ class FlutterEventMiddleware(private val flutterEvents: GeckoStateEvents) : Midd
requireNotNull(GlobalComponents.components) { "Components not initialized" }
}
/**
* Thumbnail scaling and WebP encoding are CPU-heavy and this middleware is
* normally invoked on the browser/UI dispatch path. Keep that work off the
* frame-critical thread and serialize it so periodic captures cannot build
* up a queue of competing bitmap encoders.
*/
private val thumbnailEncodingScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val thumbnailEncodingMutex = Mutex()
private var thumbnailEncodingJob: Job? = null
private fun forwardThumbnail(action: ContentAction.UpdateThumbnailAction) {
// Only the newest selected-tab preview is useful. Cancellation does not
// interrupt Bitmap.compress itself, so the mutex also prevents a newer
// request from starting a second encoder before the old one unwinds.
thumbnailEncodingJob?.cancel()
thumbnailEncodingJob = thumbnailEncodingScope.launch {
thumbnailEncodingMutex.withLock {
if (!isActive) return@withLock
val resized = action.thumbnail.resize(maxWidth = 720, maxHeight = 720)
try {
// Thumbnails are displayed at a few hundred logical pixels;
// lossless 1280x800 WebP added CPU and channel traffic with
// no visible benefit.
val bytes = resized.toWebPBytes(lossless = false, quality = 82)
if (!isActive) return@withLock
runOnUiThread {
flutterEvents.onThumbnailChange(
EventSequence.next(),
action.sessionId,
bytes,
) { _ -> }
}
} catch (error: CancellationException) {
throw error
} catch (error: Exception) {
Log.e("FlutterEventMiddleware", "Failed to encode thumbnail", error)
} finally {
if (resized !== action.thumbnail && !resized.isRecycled) {
resized.recycle()
}
}
}
}
}
@Suppress("ComplexMethod")
override fun invoke(
store: Store<BrowserState, BrowserAction>,
@@ -53,12 +109,7 @@ class FlutterEventMiddleware(private val flutterEvents: GeckoStateEvents) : Midd
) {
when (action) {
is ContentAction.UpdateThumbnailAction -> {
val resized = action.thumbnail.resize(maxWidth = 1280, maxHeight = 800);
val bytes = resized.toWebPBytes()
runOnUiThread {
flutterEvents.onThumbnailChange(EventSequence.next(), action.sessionId, bytes) { _ -> }
}
forwardThumbnail(action)
}
//UpdateReaderConnectRequiredAction seems to be the only event that is called predictable
//after a hot reload