perf(mobile): don't treat a Control Center pull as a resume (#9443)

Pulling down Control Center or Notification Center, answering a system
alert, or glancing at the app switcher moves the app to `inactive` and
straight back to `resumed`. The app never leaves the foreground and the
socket stays connected, but every resume listener treated it as a return
from the background. Each glance re-read the channel list (memberships,
metadata, unread catch-up), the four settings documents (mutes, stars,
sections, sort) and the Me groups, and tore down and rebuilt the
community presence subscription. On a heavy Builderlab account that is
about 2.6 MB per glance.

This adds `appForegroundProvider`, which follows the app lifecycle but
ignores `inactive`. The resume refreshes and both presence providers
watch it instead of the raw lifecycle, so they run only when the app
actually comes back from the background. Camera capture keeps watching
the raw lifecycle, since it has to release the camera while the app is
inactive.

### Validation

Added tests: the channel sync journey test now pulls the app through
`inactive` and back without leaving the foreground and expects no
membership read; it fails without this change (2 reads instead of 1).
The existing resume and background cases in that test still pass
unchanged. A second step lets a failed list read's retry come due while
the app is `inactive`; it is read then, not left for a resume that no
longer comes (it fails without the read gate change, 8 reads instead of
9). Full mobile test suite passes.

On an iPhone 12 mini signed in to Block's Builderlab (instrumented
profile build), pulling Control Center down and dismissing it:

| | Downloaded after dismissing it |
| --- | --- |
| Before | 2.6 MB (rosters 1.5 MB, latest messages 0.7 MB, channel
metadata 183 KB, settings, presence resubscribe) |
| After | 6.5 KB (live typing and presence only) |

The same run covered cold start, 5 minutes idle on Messages, and a
resume after 60 s in the background; the resume still refreshed the
channel list, read state and settings documents as before (2.8 MB HTTP,
2.1 MB WebSocket).

### Regressions

None expected. A real return from the background still goes through
`hidden`/`paused` first, so it triggers every refresh it did before. The
only behavior change is for `inactive` alone: no refetch, and the user's
presence no longer flips through a republish of `online`. A channel-list
read that comes due during `inactive` (a membership notice or a retry)
now runs then instead of waiting for a resume, since the socket is still
connected. A missed live event during a Control Center glance is still
caught by the next real resume or reconnect, as before for any time in
the foreground.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
This commit is contained in:
Tom Brow
2026-11-13 14:40:00 -08:00
committed by GitHub
parent 15c65c76d9
commit 9e40bf5d79
11 changed files with 80 additions and 39 deletions

View File

@@ -1,4 +1,3 @@
import 'package:flutter/widgets.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../../shared/relay/relay.dart';
@@ -67,8 +66,8 @@ class ChannelMutesNotifier extends Notifier<ChannelMutesState> {
_manager = manager;
// Resume re-read catches an EVENT a healthy socket never delivered.
ref.listen(appLifecycleProvider, (_, next) {
if (next == AppLifecycleState.resumed) manager.refreshFromRelay();
ref.listen(appForegroundProvider, (_, foreground) {
if (foreground) manager.refreshFromRelay();
});
ref.onDispose(() {

View File

@@ -1,4 +1,3 @@
import 'package:flutter/widgets.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../../shared/relay/relay.dart';
@@ -67,8 +66,8 @@ class ChannelSectionsNotifier extends Notifier<ChannelSectionsState> {
_manager = manager;
// Resume re-read catches an EVENT a healthy socket never delivered.
ref.listen(appLifecycleProvider, (_, next) {
if (next == AppLifecycleState.resumed) manager.refreshFromRelay();
ref.listen(appForegroundProvider, (_, foreground) {
if (foreground) manager.refreshFromRelay();
});
ref.onDispose(() {

View File

@@ -1,4 +1,3 @@
import 'package:flutter/widgets.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../../shared/relay/relay.dart';
@@ -74,8 +73,8 @@ class ChannelSortNotifier extends Notifier<ChannelSortState> {
_manager = manager;
// Resume re-read catches an EVENT a healthy socket never delivered.
ref.listen(appLifecycleProvider, (_, next) {
if (next == AppLifecycleState.resumed) manager.refreshFromRelay();
ref.listen(appForegroundProvider, (_, foreground) {
if (foreground) manager.refreshFromRelay();
});
ref.onDispose(() {

View File

@@ -1,4 +1,3 @@
import 'package:flutter/widgets.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../../shared/relay/relay.dart';
@@ -67,8 +66,8 @@ class ChannelStarsNotifier extends Notifier<ChannelStarsState> {
_manager = manager;
// Resume re-read catches an EVENT a healthy socket never delivered.
ref.listen(appLifecycleProvider, (_, next) {
if (next == AppLifecycleState.resumed) manager.refreshFromRelay();
ref.listen(appForegroundProvider, (_, foreground) {
if (foreground) manager.refreshFromRelay();
});
ref.onDispose(() {

View File

@@ -2,7 +2,6 @@ import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:flutter/widgets.dart';
import 'package:flutter/foundation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
@@ -273,8 +272,8 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
// Re-fetch when the app returns to foreground so channels created on
// another device while mobile was backgrounded appear immediately.
ref.listen(appLifecycleProvider, (prev, next) {
if (next != AppLifecycleState.resumed) return;
ref.listen(appForegroundProvider, (_, foreground) {
if (!foreground) return;
// Resume is published before the session hears it. Let the session
// decide first: one that reconnects reconciles when it connects, so
// refreshing here too would fetch the same list twice.

View File

@@ -248,10 +248,9 @@ extension _ChannelsNotifierLiveSubscriptions on ChannelsNotifier {
if (!_lifecycleRef.mounted) return;
_noteReopenedSubscriptions();
// Resume and reconnect read the list anyway, so a read that comes due
// in the background or offline is left to them.
if (_lifecycleRef.read(appLifecycleProvider) != AppLifecycleState.resumed) {
return;
}
// in the background or offline is left to them. Control Center and the
// like stay in the foreground and end in no resume, so they don't wait.
if (!_lifecycleRef.read(appForegroundProvider)) return;
// A retry can come due inside the gap after the read it retries.
if (_listReadGap != null) {
_listReadDueAfterGap = true;

View File

@@ -1,7 +1,6 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../shared/agents/remote_agents.dart';
@@ -49,7 +48,7 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
@override
Map<String, String> build() {
final sessionState = ref.watch(relaySessionProvider);
final lifecycle = ref.watch(appLifecycleProvider);
final foreground = ref.watch(appForegroundProvider);
final scope = ref.watch(
relayConfigProvider.select((config) => (config.baseUrl, config.nsec)),
);
@@ -80,8 +79,7 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
_resubscribe?.cancel();
_resubscribe = null;
});
if (sessionState.status == SessionStatus.connected &&
lifecycle == AppLifecycleState.resumed) {
if (sessionState.status == SessionStatus.connected && foreground) {
_poll = Timer.periodic(const Duration(seconds: 60), (_) {
// A replacement the relay never answered must not hold the slot, so a
// lost REQ costs at most one poll interval.

View File

@@ -322,7 +322,7 @@ final profileProvider = AsyncNotifierProvider<ProfileNotifier, UserProfile?>(
///
/// Sends a heartbeat every 60s while the app is active by publishing a
/// kind:20001 presence event over the relay WebSocket. Watches
/// [appLifecycleProvider] to send "away" when backgrounded.
/// [appForegroundProvider] to send "away" when backgrounded.
class PresenceNotifier extends AsyncNotifier<String> {
static const _heartbeatInterval = Duration(seconds: 60);
static const _preferenceKeyPrefix = 'buzz_presence_preference_';
@@ -346,7 +346,7 @@ class PresenceNotifier extends AsyncNotifier<String> {
_manualPresence = stored == 'away' || stored == 'offline' ? stored : null;
}
final lifecycle = ref.watch(appLifecycleProvider);
final foreground = ref.watch(appForegroundProvider);
ref.onDispose(() {
_heartbeatTimer?.cancel();
@@ -360,19 +360,13 @@ class PresenceNotifier extends AsyncNotifier<String> {
return _setPresence(manualPresence);
}
if (lifecycle == AppLifecycleState.resumed) {
if (foreground) {
_startHeartbeat();
return _setPresence('online');
} else if (lifecycle == AppLifecycleState.paused ||
lifecycle == AppLifecycleState.detached) {
_heartbeatTimer?.cancel();
_heartbeatTimer = null;
return _setPresence('away');
}
// Default: we don't know. Reflect the most recent state we set, or
// 'offline' if never set.
return Future.value('offline');
_heartbeatTimer?.cancel();
_heartbeatTimer = null;
return _setPresence('away');
}
void _startHeartbeat() {
@@ -397,8 +391,7 @@ class PresenceNotifier extends AsyncNotifier<String> {
.setString('$_preferenceKeyPrefix$pubkey', _manualPresence ?? 'auto');
}
if (_manualPresence == null &&
ref.read(appLifecycleProvider) == AppLifecycleState.resumed) {
if (_manualPresence == null && ref.read(appForegroundProvider)) {
_startHeartbeat();
} else {
_heartbeatTimer?.cancel();

View File

@@ -124,8 +124,8 @@ final meGroupsProvider = StreamProvider<MeGroups>((ref) {
}
}
ref.listen(appLifecycleProvider, (_, next) {
if (next != AppLifecycleState.resumed) return;
ref.listen(appForegroundProvider, (_, foreground) {
if (!foreground) return;
// Recover an interrupted reader by resubscribing instead of asking the user.
// Before reconnecting, leave recovery to the reconnect listener above.
if (subscriptionClosed || syncFailed) {

View File

@@ -53,3 +53,26 @@ final appLifecycleProvider =
NotifierProvider<AppLifecycleNotifier, AppLifecycleState>(
AppLifecycleNotifier.new,
);
/// Whether the app is in the foreground. Unlike [appLifecycleProvider], it
/// ignores `inactive`: pulling down Control Center or Notification Center, a
/// system alert or a glance at the app switcher passes through `inactive` and
/// back to `resumed` without leaving the foreground, and is not a resume.
class AppForegroundNotifier extends Notifier<bool> {
@override
bool build() {
ref.listen(appLifecycleProvider, (_, next) {
if (next != AppLifecycleState.inactive) {
state = next == AppLifecycleState.resumed;
}
});
return switch (ref.read(appLifecycleProvider)) {
AppLifecycleState.resumed || AppLifecycleState.inactive => true,
_ => false,
};
}
}
final appForegroundProvider = NotifierProvider<AppForegroundNotifier, bool>(
AppForegroundNotifier.new,
);

View File

@@ -15,6 +15,7 @@ import '../../helpers/fake_relay.dart';
const _channel = '11111111-1111-4111-8111-111111111111';
const _added = '22222222-2222-4222-8222-222222222222';
const _third = '33333333-3333-4333-8333-333333333333';
const _fourth = '55555555-5555-4555-8555-555555555555';
const _dm = '44444444-4444-4444-8444-444444444444';
void main() {
@@ -628,6 +629,13 @@ void main() {
expect(channels.read().requireValue.single.name, 'general');
expect(membershipReads(), 1);
// Control Center, Notification Center or a system alert passes
// through inactive without leaving the foreground: not a resume.
lifecycle(AppLifecycleState.inactive);
lifecycle(AppLifecycleState.resumed);
settle();
expect(membershipReads(), 1);
// Backgrounded while the session is still connected through its
// grace period: nothing is read until the app returns.
async.elapse(const Duration(seconds: 58));
@@ -742,6 +750,31 @@ void main() {
async.elapse(const Duration(minutes: 10));
expect(membershipReads(), 7);
// The retry comes due while Control Center is open. That is still the
// foreground and no resume follows it, so the retry is not left to one.
lifecycle(AppLifecycleState.inactive);
lifecycle(AppLifecycleState.hidden);
lifecycle(AppLifecycleState.paused);
async.elapse(const Duration(seconds: 1));
addChannel(_fourth, 'fourth');
failNextMembershipRead();
lifecycle(AppLifecycleState.hidden);
lifecycle(AppLifecycleState.inactive);
lifecycle(AppLifecycleState.resumed);
settle();
expect(membershipReads(), 8);
lifecycle(AppLifecycleState.inactive);
async.elapse(const Duration(seconds: 7));
lifecycle(AppLifecycleState.resumed);
settle();
expect(membershipReads(), 9);
expect(
names(),
unorderedEquals(['general', 'added', 'third', 'fourth']),
);
async.elapse(const Duration(minutes: 10));
expect(membershipReads(), 9);
// The connection drops and a message lands in a quiet channel. The
// unread catch-up after the reconnect fails, and is retried until the
// channel shows as unread.