mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +00:00
Ticket 6 of the [Android push design](https://github.com/block/buzz/pull/9555), building on [#9558 resolve push wakes](https://github.com/block/buzz/pull/9558). Enrollment (FCM token registration, ticket 7) landed separately in [#9811 enroll Android push](https://github.com/block/buzz/pull/9811), which also carries the Firebase build config, `POST_NOTIFICATIONS` and the auto-init switch. ## What it does A data-only FCM message wakes the app with no content. This PR turns that wake into notifications natively, with no UI: - `PushWakeService` (a `FirebaseMessagingService`) treats both a message and the deleted-messages callback as "sync now". - If the app is in the foreground it does nothing. Otherwise it starts a headless Flutter engine on `androidPushWakeMain`, which runs ticket 5's `resolvePushWake` and hands the notifications back to native code to post. - If nothing has been posted after 2 s, a generic "New activity" notification appears in the "Other" channel. The real result replaces it silently, or removes it when there is nothing to show. An 8 s native watchdog ends a run whose Dart side hangs. - One run per process. A wake that arrives mid-run joins it and sets the rerun flag from ticket 5. - Channels: Direct messages, Mentions, Other. Each conversation is one `MessagingStyle` notification, grouped under the app. Existing messages in a conversation are recovered from the active notification so a new wake appends instead of replacing. - Tapping opens the conversation through the existing push deep-link path (`pendingPushNotificationLink`), for a cold start and for a running app. This also turns on the cold-start tap handoff for Android, which was iOS-only. - The headless path sends the NIP-FI header that org-protected relays need, using the same `HostedRelayAuth` as the foreground app (background mode: a fresh assertion per wake that never records foreground failures). `resolvePushWake` gets one optional `relayHeaders` hook for it. ## Decisions - **Firebase config is build-time and never committed.** `BUZZ_FIREBASE_APP_ID`, `BUZZ_FIREBASE_API_KEY`, `BUZZ_FIREBASE_PROJECT_ID` and `BUZZ_FIREBASE_SENDER_ID` become string resources (no google-services plugin or JSON file). All four or none: a partial set fails the build, and a build with none works but has no push wake. Documented in `mobile/README.md`. - **The wake only reads the saved account session.** Its account clients share the foreground app's record, so they never save, replace or delete it. A rejected credential is dropped from the wake's memory only, which keeps a sign-in that finished mid-wake. - **No FCM token before enrollment.** Firebase Messaging's auto-init is off, so a configured build does not register with Firebase at launch. Ticket 7 requests the token when the app enrolls. - **Notifications disabled means the wake is skipped entirely**, so nothing is claimed as shown and the next wake after the user re-enables them still delivers. - **Debug hook.** Debug builds include an exported receiver that runs the same code path as the FCM service, for testing without Firebase. ## Known gaps - The foreground app does not yet write the shown-message record, so a message already read in the app can notify again after the app is backgrounded. This needs its own ticket. - `PushWakeService` is now the app's only messaging service, so it should hand `onNewToken` to the registration plugin from [#9811 enroll Android push](https://github.com/block/buzz/pull/9811). It doesn't yet. - Follow-ups now that enrollment is on main: real FCM wakes run one at a time and never join a run; a blocked or silent "Other" channel mutes a slow DM; a stale generic can make one message alert twice; NIP-FI issuance can use the whole wake budget; a consumed tap replays after process death; cold engine start registers every plugin. - Follow-ups from review: - A confirmed age restriction isn't applied to Android wakes, and the Android purge doesn't cancel posted notifications. - One unreadable entry, or a throw from `notify`, sends the whole batch, already recorded as shown, to the generic notification. - The foreground check can lag about 700 ms behind the app becoming visible. - There is no group summary, so below Android 16 several conversations show as separate cards. - On API 24 and 25 the notifications have no priority or defaults, so they don't sound. - A stall delivering the result over the channel can still use up the 1 s reserve before the watchdog. - A shown-message claim writes its marker before its watermark and prune I/O, so a stall past the 250 ms claim grace loses the message (from [#9558 Dart wake-to-notifications](https://github.com/block/buzz/pull/9558)). - A live tap during cold start can be handled before the startup tap, and the tap's target is carried in extras any app can send. - The native side has no JVM tests yet, although `app/src/test/kotlin` exists and CI runs it. A payload-contract test for `WakeNotification.fromDart` and a test of the production `_headlessRelayHeaders` wiring are follow-ups. The device runs below cover the native side, and the Dart side (payload shape, joined runs, header hook, cold-start tap) has tests. ### Validation Run on a Pixel 9a (Android 17) against a local fake relay with test data only, using a profile (AOT) build with the debug hook, since debug (JIT) builds start the Dart engine in 4 to 5 s and say little about real latency. Timings come from the `BuzzPushWake` log tags, measured from the start of the wake. | Scenario | Result | | --- | --- | | Cold wake, process killed, one DM | Notification posted at 2.0 s (engine 0.9 s, Dart ready 1.8 s), three runs within 0.1 s of each other | | Wake while the process is warm | Posted at 0.4 s | | Two conversations in one wake | One grouped notification card, each conversation its own `MessagingStyle`, posted at 2.1 s | | Relay answers in 2.4 s | Generic "New activity" at 2.0 s, replaced by the real notification at 5.8 s, generic removed, replacement did not beep (the system's `notification_alert` event shows no sound for it, while the generic did beep) | | Relay answers in 3.5 s (over the 3 s request limit) | Generic stays at 5.0 s, nothing is claimed | | Next wake after that, relay healthy | Real notification at 0.4 s and the stale generic is gone (the case fixed in `c786957`) | | Relay accepts the connection and never answers | Dart's own 3 s request timeout ends the wake at 5.0 s as incomplete, generic stays | | App in the foreground | Wake ignored, no notification; after backgrounding, the next wake delivers | | Tap, app running in background | The existing deep-link provider receives the right community, channel and message; notification dismisses | | Tap, process killed | Same | | 10 wakes in a row, debug build, app process kept alive | Network threads stay at 3 and total threads flat (53 to 58). Before the switch to dart:io, each wake left about 2 Cronet threads behind (3 to 11 over 5 wakes) | An earlier run on an Android 36 emulator gave the same behavior. Not exercised: the FCM service itself (it is not exported and there is no Firebase config), so the deleted-messages callback was not triggered, though it calls the same entry as the debug hook. The 8 s native watchdog was not reached: a hung relay is always ended earlier by Dart's request timeout, and only a hung Dart isolate would trigger it. NIP-FI against an org-protected relay is covered only by unit tests. The tap was checked up to the deep-link provider, not to the chat screen, because the fake relay does not serve the channel list the app needs to open it. On a debug (JIT) build the main thread is busy for several seconds starting the engine, so the 2 s generic timer, which runs on that thread, fired at 5.3 s. Added tests: [`android_push_wake_test.dart`](https://github.com/block/buzz/blob/android-push-wake-handling/mobile/test/shared/push/android_push_wake_test.dart) covers the native payload, joined and sequential wakes, the relay header hook, and a community whose headers fail. [`push_bridge_test.dart`](https://github.com/block/buzz/blob/android-push-wake-handling/mobile/test/shared/push/push_bridge_test.dart) covers the Android cold-start tap. ### Screenshots Before: no notification (nothing handles wakes). After, with test data, on the Pixel 9a (two conversations grouped) and on the emulator (one conversation after a cold wake): <img src="https://github.com/user-attachments/assets/d3d98784-fecc-4757-a867-0a93d5a210a5" width="300" alt="Two conversations grouped on a Pixel"> <img src="https://github.com/user-attachments/assets/1e7fea3c-7f72-4f8d-90d1-8c289cf1b740" width="300" alt="One conversation after a cold wake on an emulator"> ## Regressions - Adds the `POST_NOTIFICATIONS` permission and the Firebase Messaging and `lifecycle-process` dependencies, so the Android build and APK grow. The runtime permission prompt is not part of this PR. - Debug builds ship an exported broadcast receiver that can trigger a wake. Release builds do not include it. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost:3000> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
206 lines
6.9 KiB
Dart
206 lines
6.9 KiB
Dart
import 'dart:async';
|
|
import 'dart:io';
|
|
|
|
import 'package:buzz/shared/push/android_push_wake.dart';
|
|
import 'package:buzz/shared/push/push_wake_resolver.dart';
|
|
import 'package:buzz/shared/push/push_wake_runner.dart';
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
import 'package:http/testing.dart';
|
|
|
|
import '../../helpers/push_wake_fixture.dart';
|
|
|
|
void main() {
|
|
late Directory directory;
|
|
late PushWakeFixture fixture;
|
|
|
|
setUp(() {
|
|
directory = Directory.systemTemp.createTempSync('android-push-wake-');
|
|
fixture = PushWakeFixture(directory);
|
|
});
|
|
tearDown(() => directory.deleteSync(recursive: true));
|
|
|
|
group('the wake the native handler receives', () {
|
|
test('carries each notification with where its tap leads', () async {
|
|
final relay = fixture.addCommunity();
|
|
final room = relay.channel();
|
|
final friend = relay.person('Friend');
|
|
final dm = relay.dmChannel();
|
|
final mention = relay.message(room, friend, 'look', mention: relay.me);
|
|
final direct = relay.message(dm, friend, 'hello');
|
|
final handler = PushWakeChannelHandler(
|
|
PushWakeRunner((_) => fixture.wake()),
|
|
);
|
|
|
|
final payload = await handler.wake();
|
|
|
|
expect(payload['incomplete'], isFalse);
|
|
expect(payload['notifications'], [
|
|
{
|
|
'eventId': direct.id,
|
|
'createdAtMillis': direct.createdAt * 1000,
|
|
'title': 'Friend',
|
|
'body': 'hello',
|
|
'conversationId': '${relay.communityId}:${dm.id}',
|
|
'category': 'directMessage',
|
|
'target': {
|
|
'communityId': relay.communityId,
|
|
'channelId': dm.id,
|
|
'eventId': direct.id,
|
|
},
|
|
},
|
|
{
|
|
'eventId': mention.id,
|
|
'createdAtMillis': mention.createdAt * 1000,
|
|
'title': 'Friend',
|
|
'body': 'look',
|
|
'conversationId': '${relay.communityId}:${room.id}',
|
|
'conversationTitle': '#${room.name}',
|
|
'category': 'mention',
|
|
'target': {
|
|
'communityId': relay.communityId,
|
|
'channelId': room.id,
|
|
'eventId': mention.id,
|
|
},
|
|
},
|
|
]);
|
|
});
|
|
|
|
test('reports a wake that could not read every community', () async {
|
|
final relay = fixture.addCommunity();
|
|
relay.unreachable = true;
|
|
final handler = PushWakeChannelHandler(
|
|
PushWakeRunner((_) => fixture.wake()),
|
|
);
|
|
|
|
final payload = await handler.wake();
|
|
|
|
expect(payload['notifications'], isEmpty);
|
|
expect(payload['incomplete'], isTrue);
|
|
});
|
|
|
|
test(
|
|
'gives a wake that arrives mid-run no notifications of its own',
|
|
() async {
|
|
final relay = fixture.addCommunity();
|
|
final dm = relay.dmChannel();
|
|
final friend = relay.person('Friend');
|
|
relay.message(dm, friend, 'hello');
|
|
final hold = Completer<void>();
|
|
relay.hold = hold;
|
|
final handler = PushWakeChannelHandler(
|
|
PushWakeRunner((_) => fixture.wake()),
|
|
);
|
|
|
|
final first = handler.wake();
|
|
final second = handler.wake();
|
|
hold.complete();
|
|
final payloads = await Future.wait([first, second]);
|
|
|
|
expect((payloads[0]['notifications'] as List), hasLength(1));
|
|
expect(payloads[1], joinedWake);
|
|
},
|
|
);
|
|
|
|
test('after a run ends, the next wake gets its own result', () async {
|
|
final relay = fixture.addCommunity();
|
|
final dm = relay.dmChannel();
|
|
final friend = relay.person('Friend');
|
|
final handler = PushWakeChannelHandler(
|
|
PushWakeRunner((_) => fixture.wake()),
|
|
);
|
|
relay.message(dm, friend, 'one');
|
|
expect((await handler.wake())['notifications'] as List, hasLength(1));
|
|
|
|
relay.message(dm, friend, 'two', age: const Duration(minutes: 4));
|
|
final next = await handler.wake();
|
|
|
|
expect(
|
|
[for (final n in next['notifications'] as List) (n as Map)['body']],
|
|
['two'],
|
|
);
|
|
});
|
|
|
|
test('a run looks up no longer than the handler has left', () async {
|
|
fixture.addCommunity();
|
|
final budgets = <Duration>[];
|
|
final handler = PushWakeChannelHandler(
|
|
PushWakeRunner((budget) {
|
|
budgets.add(budget);
|
|
return fixture.wake(timeouts: PushWakeTimeouts(total: budget));
|
|
}),
|
|
);
|
|
// A slow engine start leaves less than the runner's own budget; a sent
|
|
// time past it, a missing one, or one already spent fall back to the
|
|
// budget, or to nothing.
|
|
for (final (arguments, expected) in [
|
|
({'remainingMillis': 1200}, const Duration(milliseconds: 1200)),
|
|
({'remainingMillis': 60000}, const Duration(seconds: 5)),
|
|
(null, const Duration(seconds: 5)),
|
|
({'remainingMillis': -5}, Duration.zero),
|
|
]) {
|
|
budgets.clear();
|
|
await handler.wake(remaining: wakeRemaining(arguments));
|
|
// The pass gets what is left of the run's budget, a hair under it.
|
|
expect(
|
|
(expected - budgets.single).inMilliseconds,
|
|
inInclusiveRange(0, 100),
|
|
reason: '$arguments',
|
|
);
|
|
}
|
|
});
|
|
});
|
|
|
|
test('a wake sends the relay the headers the community needs', () async {
|
|
final relay = fixture.addCommunity();
|
|
final dm = relay.dmChannel();
|
|
relay.message(dm, relay.person('Friend'), 'hello');
|
|
final seen = <String?>[];
|
|
final client = MockClient((request) async {
|
|
seen.add(request.headers['Nostr-Federated-Identity']);
|
|
return relay.handle(request);
|
|
});
|
|
final asked = <String>[];
|
|
|
|
final result = await resolvePushWake(
|
|
store: fixture.openStore(),
|
|
loadCommunities: () async => [relay.community],
|
|
httpClient: client,
|
|
relayHeaders: (community) async {
|
|
asked.add(community.id);
|
|
return {'Nostr-Federated-Identity': 'Bearer assertion'};
|
|
},
|
|
now: () => pushWakeClock,
|
|
);
|
|
|
|
expect(result.notifications, hasLength(1));
|
|
// Once for the wake, whichever queries follow.
|
|
expect(asked, [relay.communityId]);
|
|
expect(seen, isNotEmpty);
|
|
expect(seen.toSet(), {'Bearer assertion'});
|
|
});
|
|
|
|
test(
|
|
'a community whose headers cannot be read is reported incomplete',
|
|
() async {
|
|
final refused = fixture.addCommunity();
|
|
refused.message(refused.dmChannel(), refused.person('Friend'), 'hello');
|
|
final reachable = fixture.addCommunity();
|
|
final other = reachable.dmChannel();
|
|
reachable.message(other, reachable.person('Other'), 'hi');
|
|
|
|
final result = await resolvePushWake(
|
|
store: fixture.openStore(),
|
|
loadCommunities: () async => [refused.community, reachable.community],
|
|
httpClient: fixture.client,
|
|
relayHeaders: (community) async => community.id == refused.communityId
|
|
? throw StateError('no session')
|
|
: const {},
|
|
now: () => pushWakeClock,
|
|
);
|
|
|
|
expect(result.failedCommunityIds, [refused.communityId]);
|
|
expect([for (final n in result.notifications) n.body], ['hi']);
|
|
},
|
|
);
|
|
}
|