From 298543f5555bf351785979b29d0c6f0d64b5bdc1 Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Tue, 24 Nov 2026 22:27:18 -0800 Subject: [PATCH] fix(mobile): report a push wake claim it stopped waiting for (#9931) ## What An Android push wake that runs out of time can leave a claim still running. If that claim then wins, the message is recorded as shown but was never returned. No later wake finds it, so the user is never told. This makes the wake report that case, and the native handler shows its generic notification for it. - `resolvePushWake` tracks the message each community is claiming. After the claim grace it sets `PushWakeResult.unreported` when a claim is still running for a message with something to show (a message whose body is empty would not be returned anyway). It is read in the same synchronous step as the claimed-message snapshot, so a claim that finishes before the snapshot is returned, and one that finishes after it is counted. - `PushWakeRunner` reports `unreported` when any pass does, because a message lost in one pass stays lost. - The channel payload carries `unreported`. The native handler posts the named notifications, and the generic notification beside them, silently when something already alerted. If the user already cleared the generic card this wake posted at 2 seconds, it stays cleared. The generic is marked as standing in for a lost message, so later wakes, which clear an unmarked generic as before, leave it until the user clears it. A later wake that re-posts the generic keeps the mark. - It stays separate from `incomplete`, which means a later wake retries. Folding the two would show the generic beside named notifications on every retryable partial wake. - `ShownMessageStore.claim` documents that a caller that stops waiting for a claim must report it. A claim that later returns false still costs one unnecessary generic notification, which is accepted. The realistic trigger is storage that stalls after the claim marker is created, during the watermark and prune I/O in `DirectoryShownMessageStore.claim` (a pre-existing finding from the review of the Android wake handler). The store's order is unchanged. The marker has to come first for atomicity, and this signal turns the stall into a generic notification instead of silence. ## Validation - The push-wake journey test's stalled-storage step now asserts `unreported`, and a stalled claim for a message with an empty body asserts it is not set. A wake cut short in the name lookup, outside any claim, asserts it is not set and still returns its messages. The runner step asserts that a message lost in one pass is still reported after a clean rerun. The channel payload test covers both values. - Forcing the signal off fails the stalled-storage step. - `WakeNotifierGenericTest` (instrumented) drives the generic notification against the real notification manager on a Pixel 9a: an unmarked card clears on a clean wake, a kept card survives clean wakes and a later 2-second re-post, and a card the user cleared before the result is not posted again. Each step waits for the state it expects, a re-post check waits for a newer post, and checks that nothing changed run after a barrier notification. Its two updates wait 700 ms first, so Android's update rate limit can't drop them on quick reruns (12 back-to-back runs passed). Removing the cleared-card check, or dropping the mark on re-post, fails it. --------- Signed-off-by: Tom Brow Co-authored-by: studio --- PLANS/ANDROID_PUSH.md | 4 +- ...android-notifications-run-app-dart-code.md | 2 +- .../buzz/mobile/WakeNotifierGenericTest.kt | 145 ++++++++++++++++++ .../kotlin/xyz/block/buzz/mobile/PushWake.kt | 25 +-- .../buzz/mobile/PushWakeNotifications.kt | 32 +++- mobile/lib/shared/push/android_push_wake.dart | 1 + .../lib/shared/push/push_wake_resolver.dart | 28 +++- mobile/lib/shared/push/push_wake_runner.dart | 5 + .../lib/shared/push/shown_message_store.dart | 4 +- .../shared/push/android_push_wake_test.dart | 11 ++ .../shared/push/push_wake_journey_test.dart | 55 ++++++- 11 files changed, 294 insertions(+), 18 deletions(-) create mode 100644 mobile/android/app/src/androidTest/kotlin/xyz/block/buzz/mobile/WakeNotifierGenericTest.kt diff --git a/PLANS/ANDROID_PUSH.md b/PLANS/ANDROID_PUSH.md index 2afdf5210c..3063b9ecc1 100644 --- a/PLANS/ANDROID_PUSH.md +++ b/PLANS/ANDROID_PUSH.md @@ -83,10 +83,10 @@ Decisions recorded as ADRs: [0004](../docs/adr/0004-push-gateway-hides-device-pl **Mobile, Android native** -- A Firebase messaging service receives the wake. When the app is in the foreground (a native lifecycle check), it does nothing: the running app already shows new messages. Otherwise it starts a background Flutter engine running the wake-to-notification entrypoint and posts the result directly. The category is known only after the fetch, so no notification is posted before it. If nothing has been posted after about 2 s, it posts a generic "New activity" notification in a third "Other" category, which the real result replaces silently, and which is removed when the result is that there is nothing to show. A native watchdog finishes the work inside the platform's time limit even if Dart never answers. +- A Firebase messaging service receives the wake. When the app is in the foreground (a native lifecycle check), it does nothing: the running app already shows new messages. Otherwise it starts a background Flutter engine running the wake-to-notification entrypoint and posts the result directly. The category is known only after the fetch, so no notification is posted before it. If nothing has been posted after about 2 s, it posts a generic "New activity" notification in a third "Other" category, which the real result replaces silently, and which is removed when the result is that there is nothing to show. When the result reports a message it claimed but could not return, the generic notification stays, beside the named notifications, and later wakes leave it. A native watchdog finishes the work inside the platform's time limit even if Dart never answers. - FCM token registration and rotation feed the same enrollment and endpoint-rotation flow iOS uses. - The app generates an Android Keystore key with the gateway's challenge and sends its attestation chain at enrollment. -- Notification categories are "Direct messages", "Mentions" and "Other" (only the slow-fetch generic notification). Notifications use the platform's messaging style, grouped per conversation. A tap opens the conversation through the app's existing deep-link handling. +- Notification categories are "Direct messages", "Mentions" and "Other" (only the generic notification, for a slow fetch or a message claimed but not returned). Notifications use the platform's messaging style, grouped per conversation. A tap opens the conversation through the app's existing deep-link handling. - The Android 13+ notification permission prompt appears at the same point iOS asks. - Firebase configuration is a build-time setting supplied by each distributor, never committed. diff --git a/docs/adr/0006-android-notifications-run-app-dart-code.md b/docs/adr/0006-android-notifications-run-app-dart-code.md index 55126270c9..cddc6dc269 100644 --- a/docs/adr/0006-android-notifications-run-app-dart-code.md +++ b/docs/adr/0006-android-notifications-run-app-dart-code.md @@ -2,7 +2,7 @@ On iOS, a native Swift notification service extension fetches and formats each notification. On Android, the push handler instead starts the app's Dart code in a background engine, without the UI, and that code fetches the message from the relay and builds the notification. This reuses the app's relay, sign-in and formatting code rather than porting the iOS extension to Kotlin. A prototype showed it fits Android's time limit for handling a push: on an emulator, the real text appeared about 0.1 s after a cold wake, and about 1 s with the CPU slowed 8x, against a budget of about 10 s. -The handler posts the fetched notifications directly, because the category (and so the channel the user may have silenced) is known only after the fetch. If nothing is posted within about 2 s, it posts a generic notification in a separate "Other" category, which the real result replaces silently. A slow or failed fetch therefore still leaves a visible notification, and Android deprioritizes apps whose high-priority pushes show nothing. While the app is in the foreground the handler does nothing. Unlike the iOS extension, which can only rewrite the push it was handed, the handler posts every eligible unshown message it finds, grouped per conversation, so a wake means "sync now". The background path uses its own short network timeouts and a native watchdog, because the app's normal connect and sign-in timeouts are longer than the budget. +The handler posts the fetched notifications directly, because the category (and so the channel the user may have silenced) is known only after the fetch. If nothing is posted within about 2 s, it posts a generic notification in a separate "Other" category, which the real result replaces silently. When the result reports a message it claimed but could not return, the generic notification stays, beside the named notifications, until the user clears it. A slow or failed fetch therefore still leaves a visible notification, and Android deprioritizes apps whose high-priority pushes show nothing. While the app is in the foreground the handler does nothing. Unlike the iOS extension, which can only rewrite the push it was handed, the handler posts every eligible unshown message it finds, grouped per conversation, so a wake means "sync now". The background path uses its own short network timeouts and a native watchdog, because the app's normal connect and sign-in timeouts are longer than the budget. ## Considered options diff --git a/mobile/android/app/src/androidTest/kotlin/xyz/block/buzz/mobile/WakeNotifierGenericTest.kt b/mobile/android/app/src/androidTest/kotlin/xyz/block/buzz/mobile/WakeNotifierGenericTest.kt new file mode 100644 index 0000000000..31988c3be2 --- /dev/null +++ b/mobile/android/app/src/androidTest/kotlin/xyz/block/buzz/mobile/WakeNotifierGenericTest.kt @@ -0,0 +1,145 @@ +package xyz.block.buzz.mobile + +import android.Manifest +import android.os.Build +import android.os.SystemClock +import android.service.notification.StatusBarNotification +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlin.test.fail + +/** + * The generic notification against the real notification manager: a card + * kept for a lost message survives later wakes, and one the user cleared + * stays cleared. + */ +@RunWith(AndroidJUnit4::class) +class WakeNotifierGenericTest { + private val context = InstrumentationRegistry.getInstrumentation().targetContext + private val manager = NotificationManagerCompat.from(context) + private val notifier = WakeNotifier(context) + + @Before fun setUp() { + if (Build.VERSION.SDK_INT >= 33) { + InstrumentationRegistry.getInstrumentation().uiAutomation + .grantRuntimePermission(context.packageName, Manifest.permission.POST_NOTIFICATIONS) + } + notifier.createChannels() + manager.cancelAll() + } + + @After fun tearDown() = manager.cancelAll() + + @Test fun lostGenericJourney() { + // A clean wake clears an unmarked generic, as before. + notifier.postGeneric() + awaitGeneric(Generic.SHOWING) + notifier.cancelGeneric() + awaitGeneric(Generic.NONE) + + // The 2-second card is still up when the result reports a lost + // message: it is kept, and later clean wakes leave it. + notifier.postGeneric() + val timerCard = awaitGeneric(Generic.SHOWING) + paceUpdate() + assertTrue(notifier.keepGeneric(shownThisWake = true, silent = true)) + awaitRepost(timerCard, Generic.LOST) + notifier.cancelGeneric() + drain() + assertEquals(Generic.LOST, generic()) + + // A later wake's 2-second card re-posts it and keeps the mark. + val kept = activeGeneric()!! + paceUpdate() + notifier.postGeneric() + awaitRepost(kept, Generic.LOST) + + // The user clears it. + clearGeneric() + awaitGeneric(Generic.NONE) + + // The user clears the 2-second card before the result reports a lost + // message: it is not posted again. + notifier.postGeneric() + awaitGeneric(Generic.SHOWING) + clearGeneric() + awaitGeneric(Generic.NONE) + assertFalse(notifier.keepGeneric(shownThisWake = true, silent = true)) + drain() + assertEquals(Generic.NONE, generic()) + + // Nothing posted this wake yet: the kept card is posted. + assertTrue(notifier.keepGeneric(shownThisWake = false, silent = false)) + awaitGeneric(Generic.LOST) + } + + private enum class Generic { NONE, SHOWING, LOST } + + // As a swipe or tap does: the platform cancels the card, not the handler. + private fun clearGeneric() = manager.cancel("generic", 2) + + // The notification service applies posts and cancels asynchronously, so + // each step waits, within a bound, for the state it expects. + private fun awaitGeneric(expected: Generic): StatusBarNotification? { + await("generic $expected, was ${generic()}") { generic() == expected } + return activeGeneric() + } + + // Waits for a new post of the card, so the state read is the re-post's + // and not the record it replaced. + private fun awaitRepost(previous: StatusBarNotification?, expected: Generic) { + await("a re-post of the generic") { + activeGeneric()?.let { it.postTime != previous?.postTime } == true + } + assertEquals(expected, generic()) + } + + // Android silently drops an update to a showing card while the app + // posts faster than max_notification_enqueue_rate (5 a second), and the + // estimate carries over between runs. 700 ms with no post keeps the + // rate under that, so quick reruns don't shed the test's updates. + private fun paceUpdate() = SystemClock.sleep(700) + + // Before asserting that nothing changed: a barrier card posted and + // cancelled after the step is applied after it too. + private fun drain() { + manager.notify( + "barrier", + 3, + NotificationCompat.Builder(context, WakeNotifier.OTHER_CHANNEL) + .setSmallIcon(android.R.drawable.stat_notify_chat) + .build(), + ) + await("the barrier card") { manager.activeNotifications.any { it.tag == "barrier" } } + manager.cancel("barrier", 3) + await("the barrier card to clear") { manager.activeNotifications.none { it.tag == "barrier" } } + } + + private fun await(what: String, condition: () -> Boolean) { + val deadline = SystemClock.uptimeMillis() + 5_000 + while (!condition()) { + if (SystemClock.uptimeMillis() > deadline) fail("timed out waiting for $what") + Thread.sleep(20) + } + } + + private fun activeGeneric(): StatusBarNotification? { + val active = manager.activeNotifications.filter { it.tag == "generic" && it.id == 2 } + assertTrue(active.size <= 1) + return active.firstOrNull() + } + + private fun generic(): Generic { + val card = activeGeneric() ?: return Generic.NONE + return if (card.notification.extras.getBoolean("xyz.block.buzz.mobile.lost")) Generic.LOST else Generic.SHOWING + } +} diff --git a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWake.kt b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWake.kt index 4564ab9812..48e51bd159 100644 --- a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWake.kt +++ b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWake.kt @@ -27,8 +27,9 @@ import java.util.concurrent.TimeUnit * * If nothing has been posted after [GENERIC_AFTER_MS] the handler posts a * generic notification in the "Other" channel, which the result then replaces - * silently, or removes when it finds nothing. A watchdog ends the work at - * [WATCHDOG_MS] whatever Dart does, inside the time FCM gives a handler, and + * silently, or removes when it finds nothing. It stays, beside any named ones, + * when the result reports a message it lost track of. A watchdog ends the work + * at [WATCHDOG_MS] whatever Dart does, inside the time FCM gives a handler, and * leaves the generic notification when no result came. * * One run exists per process. A wake that arrives while it runs is passed to @@ -195,21 +196,27 @@ internal object PushWake { log("dart_result") val notifications = (map["notifications"] as List<*>).map { WakeNotification.fromDart(it) } answered = true + if (notifications.isNotEmpty()) { + notifier.postConversations(notifications, silent = genericShown) + log("posted count=${notifications.size}") + } when { - notifications.isNotEmpty() -> { - notifier.postConversations(notifications, silent = genericShown) - log("posted count=${notifications.size}") - removeGeneric() + // A message claimed but never returned can't be named, and no + // later wake finds it, so the generic notification stands in + // for it, beside any named ones, until the user clears it. + map["unreported"] == true -> { + val silent = genericShown || notifications.isNotEmpty() + if (notifier.keepGeneric(genericShown, silent)) genericShown = true } - map["incomplete"] == true -> showGeneric() + notifications.isEmpty() && map["incomplete"] == true -> showGeneric() else -> removeGeneric() } } - private fun showGeneric() { + private fun showGeneric(silent: Boolean = false) { if (genericShown) return genericShown = true - notifier.postGeneric() + notifier.postGeneric(silent) } /** Also clears the generic notification an earlier run left behind. */ diff --git a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWakeNotifications.kt b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWakeNotifications.kt index 7135816801..583a91106d 100644 --- a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWakeNotifications.kt +++ b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWakeNotifications.kt @@ -4,6 +4,7 @@ import android.app.PendingIntent import android.content.Context import android.content.Intent import android.net.Uri +import android.os.Bundle import androidx.core.app.NotificationChannelCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat @@ -103,6 +104,7 @@ internal class WakeNotifier(private val context: Context) { private const val GENERIC_ID = 2 private const val GENERIC_TAG = "generic" private const val EVENT_ID_EXTRA = "eventId" + private const val LOST_EXTRA = "xyz.block.buzz.mobile.lost" private fun conversationTag(conversationId: String) = "conversation:$conversationId" } @@ -185,7 +187,12 @@ internal class WakeNotifier(private val context: Context) { } } - fun postGeneric() { + /** + * [silent] posts it without alerting, beside notifications that did. + * [lost] marks it as standing in for a message no wake can name, so + * [cancelGeneric] leaves it. Re-posting a marked one keeps the mark. + */ + fun postGeneric(silent: Boolean = false, lost: Boolean = false) { val tap = PendingIntent.getActivity( context, GENERIC_ID, @@ -200,11 +207,32 @@ internal class WakeNotifier(private val context: Context) { .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setAutoCancel(true) .setContentIntent(tap) + .setSilent(silent) + .addExtras(Bundle().apply { putBoolean(LOST_EXTRA, lost || genericLost()) }) .build() AgeRestriction.unlessRestricted { manager.notify(GENERIC_TAG, GENERIC_ID, notification) } } - fun cancelGeneric() = manager.cancel(GENERIC_TAG, GENERIC_ID) + /** Leaves a generic notification that stands in for a lost message. */ + fun cancelGeneric() { + if (!genericLost()) manager.cancel(GENERIC_TAG, GENERIC_ID) + } + + /** + * Posts the generic notification marked lost, so later wakes leave it. A + * card this wake already showed ([shownThisWake]), and the user has since + * cleared, stays cleared. Returns whether it is showing. + */ + fun keepGeneric(shownThisWake: Boolean, silent: Boolean): Boolean { + if (shownThisWake && activeGeneric() == null) return false + postGeneric(silent, lost = true) + return true + } + + private fun genericLost(): Boolean = activeGeneric()?.notification?.extras?.getBoolean(LOST_EXTRA) == true + + private fun activeGeneric() = + manager.activeNotifications.firstOrNull { it.tag == GENERIC_TAG && it.id == GENERIC_ID } private fun existingStyle(tag: String): NotificationCompat.MessagingStyle? = manager.activeNotifications diff --git a/mobile/lib/shared/push/android_push_wake.dart b/mobile/lib/shared/push/android_push_wake.dart index b46eab67fe..83b424ae8a 100644 --- a/mobile/lib/shared/push/android_push_wake.dart +++ b/mobile/lib/shared/push/android_push_wake.dart @@ -52,6 +52,7 @@ Map pushWakeChannelPayload(PushWakeResult result) => { }, ], 'incomplete': result.incomplete, + 'unreported': result.unreported, }; /// Answers the native handler's wake requests from a [PushWakeRunner]. diff --git a/mobile/lib/shared/push/push_wake_resolver.dart b/mobile/lib/shared/push/push_wake_resolver.dart index 9389471f8c..d826f4e68d 100644 --- a/mobile/lib/shared/push/push_wake_resolver.dart +++ b/mobile/lib/shared/push/push_wake_resolver.dart @@ -131,6 +131,7 @@ class PushWakeResult { required this.notifications, this.failedCommunityIds = const [], this.interrupted = false, + this.unreported = false, }); /// Every eligible unshown message, newest first, within the caps. @@ -144,6 +145,12 @@ class PushWakeResult { /// say which communities it missed. final bool interrupted; + /// Whether a claim was still running when the wake stopped waiting for it. + /// If it wins, its message is recorded as shown but was never returned, so + /// no later wake finds it, and the caller shows its generic notification + /// beside any others. Unlike [incomplete], a retry can't recover it. + final bool unreported; + /// Whether the wake could not look everywhere. With no [notifications] the /// caller shows its generic notification, so the wake is never silent. bool get incomplete => interrupted || failedCommunityIds.isNotEmpty; @@ -265,6 +272,13 @@ Future resolvePushWake({ await Future.wait( run.claims, ).timeout(_claimGrace, onTimeout: () => const []); + // Read with the claimed snapshot below, with no await between: a claim + // that finishes after this point is not returned, so it is unreported. + // A message with nothing to show would not be returned anyway. Its body + // is formatted only here, so claims that answer in time never pay for it. + final unreported = run.claiming.values.any( + (event) => notificationBody(event.content).isNotEmpty, + ); for (final community in eligible) { if (!run.done.contains(community.id)) run.failed.add(community.id); } @@ -276,6 +290,7 @@ Future resolvePushWake({ return PushWakeResult( notifications: capPushWakeNotifications(run.notifications), failedCommunityIds: run.failed.toSet().toList()..sort(), + unreported: unreported, ); } finally { timer.cancel(); @@ -295,6 +310,10 @@ class _WakeRun { final done = {}; final claims = >[]; + /// The message each community is claiming now, until its claim answers. + /// A community claims one message at a time. + final claiming = {}; + /// What each community running now has claimed so far, which is returned if /// the wake ends before the community does. final claimed = >{}; @@ -523,12 +542,19 @@ Future _resolveCommunity( // A claim that fails (storage full, say) ends this community's run. // The messages claimed before it are returned, since they are already // recorded as shown, and the community is reported as incomplete. + final bool won; + run.claiming[community.id] = event; try { - if (!await store.claim(community.id, event.id, createdAt)) continue; + won = await store.claim(community.id, event.id, createdAt); } on Object { complete = false; break; + } finally { + // Nothing awaits between here and adding the message to `claimed`, + // so a claim the wake has stopped waiting for is still counted. + run.claiming.remove(community.id); } + if (!won) continue; final body = notificationBody(event.content); // A message with no text (only markup) has nothing to show, but it is // recorded so it is not looked at again. diff --git a/mobile/lib/shared/push/push_wake_runner.dart b/mobile/lib/shared/push/push_wake_runner.dart index 557731a7af..383888a7c0 100644 --- a/mobile/lib/shared/push/push_wake_runner.dart +++ b/mobile/lib/shared/push/push_wake_runner.dart @@ -56,6 +56,7 @@ class PushWakeRunner { var first = true; var interrupted = false; var lastInterrupted = false; + var unreported = false; do { _rerun = false; final PushWakeResult result; @@ -73,6 +74,9 @@ class PushWakeRunner { } first = false; notifications.addAll(result.notifications); + // A message claimed but not returned stays lost whatever later passes + // find, so any pass reports it. + unreported = unreported || result.unreported; // Only the last pass says what is still unread, because a community // that failed once may have been read by the next, and a pass that ran // out of time may have been followed by one that finished. @@ -87,6 +91,7 @@ class PushWakeRunner { // A wake that arrived during the last pass and got no rerun for lack of // budget was never looked up, so the caller must fall back for it. interrupted: interrupted || lastInterrupted || _rerun, + unreported: unreported, ); } } diff --git a/mobile/lib/shared/push/shown_message_store.dart b/mobile/lib/shared/push/shown_message_store.dart index acc43fd3fc..a61a787ffc 100644 --- a/mobile/lib/shared/push/shown_message_store.dart +++ b/mobile/lib/shared/push/shown_message_store.dart @@ -28,7 +28,9 @@ abstract interface class ShownMessageStore { /// /// Callers claim before they post, so a message is posted at most once. If /// posting then fails, the message is not offered again, which is better - /// than repeating it. + /// than repeating it. For the same reason, a caller that stops waiting for a + /// claim must report it as lost (`PushWakeResult.unreported`), even though + /// the claim may yet return false and cost only a needless fallback. Future claim(String community, String eventId, DateTime createdAt); } diff --git a/mobile/test/shared/push/android_push_wake_test.dart b/mobile/test/shared/push/android_push_wake_test.dart index afd50edceb..a3f43e219e 100644 --- a/mobile/test/shared/push/android_push_wake_test.dart +++ b/mobile/test/shared/push/android_push_wake_test.dart @@ -76,6 +76,17 @@ void main() { expect(payload['notifications'], isEmpty); expect(payload['incomplete'], isTrue); + expect(payload['unreported'], isFalse); + + // A message the wake lost track of is reported too, so the handler + // shows its generic notification beside any named ones. + final lost = await PushWakeChannelHandler( + PushWakeRunner( + (_) async => + const PushWakeResult(notifications: [], unreported: true), + ), + ).wake(); + expect(lost['unreported'], isTrue); }); test( diff --git a/mobile/test/shared/push/push_wake_journey_test.dart b/mobile/test/shared/push/push_wake_journey_test.dart index 666a0a0b62..bc6c76cde0 100644 --- a/mobile/test/shared/push/push_wake_journey_test.dart +++ b/mobile/test/shared/push/push_wake_journey_test.dart @@ -663,8 +663,8 @@ void main() { // Storage that stalls on one claim past the budget doesn't hold the // wake. Messages not yet claimed stay unclaimed for the next wake. A // claim that only wins after the wake answered is recorded as shown but - // never returned, so its community is reported incomplete and the - // caller falls back. + // never returned, so its community is reported incomplete, the wake is + // marked unreported, and the caller falls back. relay.silent = false; final friend = relay.person('Friend'); final sent = [ @@ -697,6 +697,7 @@ void main() { final partialIds = partial.notifications.map((n) => n.eventId).toList(); expect(partialIds, isNot(contains(heldId))); expect(partial.failedCommunityIds, [relay.communityId]); + expect(partial.unreported, isTrue); final rest = await fixture.wake(); expect(rest.incomplete, isFalse); expect( @@ -710,6 +711,8 @@ void main() { final unnamed = await fixture.wake(timeouts: tight); expect(lookup.elapsed, lessThan(const Duration(seconds: 2))); expect(unnamed.notifications.map((n) => n.eventId), [late.id]); + // Cut short outside any claim, everything it claimed is returned. + expect(unnamed.unreported, isFalse); // Storage that never answers for one community holds back neither the // others nor what it claimed before it stalled, and the community is @@ -740,6 +743,26 @@ void main() { fine.id, claimedFirst.id, }); + // The claim still running may yet win, recording a message the wake + // never returned, so the wake says so. + expect(cutShort.unreported, isTrue); + + // A stalled claim for a message with nothing to show would not have + // been returned anyway, so nothing is lost. + final blank = fixture.addCommunity(); + blank.message(blank.dmChannel(), blank.person('Friend'), ' \n\t '); + final blankStall = await fixture + .wake( + store: StalledShownMessageStore( + fixture.openStore(), + blank.communityId, + succeed: 0, + ), + timeouts: tight, + ) + .timeout(const Duration(seconds: 3)); + expect(blankStall.failedCommunityIds, [blank.communityId]); + expect(blankStall.unreported, isFalse); // Once the budget is spent, nothing more is sent to a relay. final gate = Completer(); @@ -911,8 +934,36 @@ void main() { for (final result in await Future.wait([eighth, ninth])) { expect(result.notifications, isEmpty); expect(result.incomplete, isTrue); + expect(result.unreported, isFalse); } expect(failingPasses, 2); + + // A message lost by one pass stays lost, so a clean rerun still + // reports it. + var lostPasses = 0; + final losing = PushWakeRunner((budget) async { + final result = await fixture.wake( + timeouts: PushWakeTimeouts(total: budget), + ); + return ++lostPasses > 1 + ? result + : PushWakeResult( + notifications: result.notifications, + unreported: true, + ); + }); + final lostHeld = relay.hold = Completer(); + final lostBefore = relay.queries.length; + final tenth = losing.wake(); + await untilQueries(relay, lostBefore + 1); + final eleventh = losing.wake(); + lostHeld.complete(); + relay.hold = null; + for (final result in await Future.wait([tenth, eleventh])) { + expect(result.incomplete, isFalse); + expect(result.unreported, isTrue); + } + expect(lostPasses, 2); }); }); }