notifications: group mail by account; messaging-style accumulation
- Commit
13695cf11f798eaf46b00a143a61455b5bc5e99b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-20 23:08 UTC (15 days ago)
- Parents
a54e9f8
Email notifications now group per account with one summary (InboxStyle, 'N new messages', tap opens that account's inbox). Children keep their IDs so cancel-on-read works unchanged, and the summary is dropped only when the group empties - including via the mark-read/delete receiver. Communicate's incoming notification used to overwrite the previous message; it now recovers the live notification's MessagingStyle and appends (capped 25, re-deliveries deduped), so process death loses nothing and cancel-on-open still resets accumulation. No cross-conversation summary: conversations live in the system conversations section keyed by shortcut, and lines own different channels. Tests updated for both behaviours. Verified: email 571, communicate 1970 tests, 0 failures.
Diff
communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.kt b/communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.ktindex 4a703b95e6..84ce037e50 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.kt@@ -57,10 +57,21 @@ object ConversationSpace { private const val CONVERSATION_CATEGORY = "com.google.android.category.CONVERSATIONS" - // One notification per conversation: newer messages replace the previous one under the same tag,- // which is what makes a thread accumulate in the shade rather than stacking N separate entries.+ // One notification per conversation, under the same tag/id: re-posting it+ // updates the shade entry in place rather than stacking N entries. Since+ // this change the re-post carries every still-unread message in its+ // MessagingStyle (recovered from the previous posting, see notifyIncoming),+ // so the entry accumulates messages instead of showing only the newest.+ // No cross-conversation group summary: conversations already live in the+ // system's dedicated conversations section keyed by shortcut/bubble, and+ // each line owns a different channel — a single summary would have to pick+ // one line's channel/shortcut and would fight that ranking, so grouping+ // here is per-conversation only. private const val MESSAGE_NOTIFICATION_ID = 1 + /** Cap on messages retained in one conversation's [NotificationCompat.MessagingStyle]. */+ private const val MAX_MESSAGING_STYLE_MESSAGES = 25+ /** Stable per-conversation id, unique across lines. */ fun shortcutId(target: ConversationTarget): String { val key = target.remoteId@@ -174,11 +185,39 @@ object ConversationSpace { val shortcutId = pushShortcut(context, target) val sender = person(context, target) val self = Person.Builder().setName(context.getString(R.string.you)).build()+ val nm = context.getSystemService(NotificationManager::class.java) ?: return++ // Accumulate unread messages: recover the MessagingStyle from the+ // notification currently posted under this conversation's tag/id and+ // carry its messages forward. Reading the live notification (rather+ // than an in-memory list) survives process death, and cancelIncoming+ // removing that notification is exactly what resets the accumulation+ // once the conversation is read — no extra state to keep in sync.+ val previous = runCatching {+ nm.activeNotifications+ .firstOrNull { it.tag == shortcutId && it.id == MESSAGE_NOTIFICATION_ID }+ ?.notification+ ?.let { NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(it) }+ ?.messages+ .orEmpty()+ }.getOrDefault(emptyList()) val messagingStyle = NotificationCompat.MessagingStyle(self) .setGroupConversation(target.isGroup) .setConversationTitle(target.title.takeIf { target.isGroup })- .addMessage(body, timestamp, sender)+ val retained = previous.takeLast(MAX_MESSAGING_STYLE_MESSAGES - 1)+ for (message in retained) {+ val text = message.text ?: continue+ messagingStyle.addMessage(text, message.timestamp, message.person)+ }+ // An exact re-delivery of the newest message (sync retry) must not+ // duplicate it; anything else appends, never replaces.+ val alreadyPresent = retained.any {+ it.text?.toString() == body && it.timestamp == timestamp+ }+ if (!alreadyPresent) {+ messagingStyle.addMessage(body, timestamp, sender)+ } val contentIntent = PendingIntent.getActivity( context,@@ -228,7 +267,6 @@ object ConversationSpace { .extend(carExtender(target.title ?: target.personName, body, smallIcon)) .build() - val nm = context.getSystemService(NotificationManager::class.java) ?: return nm.notify(shortcutId, MESSAGE_NOTIFICATION_ID, notification) }
communicate/src/test/java/com/vayunmathur/communicate/notifications/ConversationSpaceSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/notifications/ConversationSpaceSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/notifications/ConversationSpaceSlice4Test.ktindex dc809c75f3..b62451894b 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/notifications/ConversationSpaceSlice4Test.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/notifications/ConversationSpaceSlice4Test.kt@@ -98,7 +98,8 @@ class ConversationSpaceSlice4Test { val first = nm.activeNotifications.size assertEquals(1, first) - // A second message in the same thread replaces, not stacks.+ // A second message in the same thread re-posts (not stacks), but its+ // MessagingStyle now accumulates both unread messages. ConversationSpace.notifyIncoming( context = context, target = target(),@@ -108,6 +109,11 @@ class ConversationSpaceSlice4Test { smallIcon = android.R.drawable.sym_action_call, ) assertEquals(1, nm.activeNotifications.size)+ val accumulated = androidx.core.app.NotificationCompat.MessagingStyle+ .extractMessagingStyleFromNotification(nm.activeNotifications.single().notification)+ ?.messages+ ?.map { it.text.toString() }+ assertEquals(listOf("hello", "hello again"), accumulated) // A different conversation gets its own slot. ConversationSpace.notifyIncoming(@@ -121,6 +127,33 @@ class ConversationSpaceSlice4Test { assertEquals(2, nm.activeNotifications.size) } + @Test+ fun `cancelIncoming clears the notification and resets accumulation`() {+ val nm = context.getSystemService(android.app.NotificationManager::class.java)!!+ ConversationSpace.ensureIncomingChannel(+ context, ConversationSpace.SIM_CHANNEL_ID, "SMS", "incoming sms",+ )+ fun post(body: String, ts: Long) = ConversationSpace.notifyIncoming(+ context = context, target = target(),+ channelId = ConversationSpace.SIM_CHANNEL_ID, body = body, timestamp = ts,+ smallIcon = android.R.drawable.sym_action_call,+ )+ post("one", 1_700_000_000_000L)+ post("two", 1_700_000_000_001L)+ assertEquals(1, nm.activeNotifications.size)++ // Same tag/id contract as before: cancelIncoming removes it.+ ConversationSpace.cancelIncoming(context, target())+ assertEquals(0, nm.activeNotifications.size)++ // The next message starts a fresh style, not the read history.+ post("three", 1_700_000_000_002L)+ val texts = androidx.core.app.NotificationCompat.MessagingStyle+ .extractMessagingStyleFromNotification(nm.activeNotifications.single().notification)+ ?.messages?.map { it.text.toString() }+ assertEquals(listOf("three"), texts)+ }+ @Test fun `pushShortcut returns the stable id and remove clears it`() { val id = ConversationSpace.pushShortcut(context, target())
email/src/main/java/com/vayunmathur/email/platform/EmailNotificationActionReceiver.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailNotificationActionReceiver.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailNotificationActionReceiver.ktindex 4bceda1a45..82372e652d 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailNotificationActionReceiver.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailNotificationActionReceiver.kt@@ -66,6 +66,7 @@ class EmailNotificationActionReceiver : BroadcastReceiver() { } } NotificationManagerCompat.from(context).cancel(notifId)+ EmailNotifications.cancelSummaryIfNoChildren(context, accountEmail) } catch (_: Exception) { Log.status("EmailNotifAction", "Action $action failed") } finally {
email/src/main/java/com/vayunmathur/email/platform/EmailNotifications.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailNotifications.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailNotifications.ktindex 4accfbab29..cddc037275 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailNotifications.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailNotifications.kt@@ -26,6 +26,22 @@ object EmailNotifications { /** Stable per-account channel id so each account gets its own OS toggle. */ private fun channelId(accountEmail: String) = CHANNEL_PREFIX + accountEmail + /**+ * Stable notification group key for one account. It is deliberately the+ * account email itself: every child for the account shares it, and the+ * single group-summary notification (below) joins the same group.+ */+ private fun groupKey(accountEmail: String) = accountEmail++ /**+ * Id of the one group-summary notification for [accountEmail]. Derived+ * from a summary-specific string, not from any message id, so it never+ * reuses a child's [notificationId] for the messages in the tests/callers+ * (a child id is `accountHash * 31 xor messageId`).+ */+ private fun summaryNotificationId(accountEmail: String): Int =+ "summary::${channelId(accountEmail)}".hashCode()+ /** Idempotent — creates a per-account notification channel. */ fun ensureChannel(context: Context, accountEmail: String) { context.ensureNotificationChannel(@@ -58,6 +74,7 @@ object EmailNotifications { for (msg in ordered) { postOne(nm, context, accountEmail, msg) }+ postSummary(nm, context, accountEmail, ordered) } /**@@ -76,12 +93,133 @@ object EmailNotifications { // Notifications revoked — nothing to cancel. } }+ // Child ids above are unchanged, so cancel-on-read keeps working.+ // Drop the summary only once its group has no children left;+ // otherwise it must stay to summarise the remaining unread mail.+ for (accountEmail in messages.map { it.accountEmail }.distinct()) {+ cancelSummaryIfNoChildren(context, accountEmail)+ }+ }++ /**+ * Cancel [accountEmail]'s group summary iff no grouped child remains.+ * Also called after a notification action (mark-read/delete) dismisses+ * a single child directly by id, so the summary never outlives its group.+ */+ fun cancelSummaryIfNoChildren(context: Context, accountEmail: String) {+ val manager = context.getSystemService(NotificationManager::class.java) ?: return+ val hasChild = runCatching {+ manager.activeNotifications.any { sbn ->+ sbn.id != summaryNotificationId(accountEmail) &&+ sbn.notification.group == groupKey(accountEmail)+ }+ }.getOrDefault(true) // On any doubt keep the summary.+ if (hasChild) return+ try {+ NotificationManagerCompat.from(context).cancel(summaryNotificationId(accountEmail))+ } catch (_: SecurityException) {+ // Notifications revoked — nothing to cancel.+ } } /** Cancel the notification for a single message (see [cancelForMessages]). */ fun cancelForMessage(context: Context, msg: EmailMessage) = cancelForMessages(context, listOf(msg)) + /**+ * Post (or refresh) the single group-summary notification for an account.+ *+ * Lines/count are rebuilt from the account's currently active grouped+ * children when the system can report them, so successive sync batches+ * accumulate in the summary instead of the newest batch replacing the+ * unread picture; [ordered] is the fallback when they cannot be read.+ * Re-posting under [summaryNotificationId] keeps it one-per-account.+ */+ private fun postSummary(+ nm: NotificationManagerCompat,+ context: Context,+ accountEmail: String,+ ordered: List<EmailMessage>,+ ) {+ try {+ nm.notify(summaryNotificationId(accountEmail), buildSummary(context, accountEmail, ordered))+ } catch (_: SecurityException) {+ // Pre-permission grant on Android 13+ — silently drop.+ }+ }++ private fun buildSummary(+ context: Context,+ accountEmail: String,+ ordered: List<EmailMessage>,+ ): Notification {+ val activeChildren = runCatching {+ context.getSystemService(NotificationManager::class.java)+ ?.activeNotifications+ ?.filter { sbn ->+ sbn.id != summaryNotificationId(accountEmail) &&+ sbn.notification.group == groupKey(accountEmail)+ }+ ?.sortedByDescending { it.notification.`when` }+ .orEmpty()+ }.getOrDefault(emptyList())++ val lines: List<String>+ val count: Int+ val latestWhen: Long+ if (activeChildren.isNotEmpty()) {+ count = activeChildren.size+ latestWhen = activeChildren.first().notification.`when`+ lines = activeChildren.map { sbn ->+ val title = sbn.notification.extras.getCharSequence("android.title")?.toString()+ val text = sbn.notification.extras.getCharSequence("android.text")?.toString()+ listOfNotNull(title?.takeIf { it.isNotBlank() }, text?.takeIf { it.isNotBlank() })+ .joinToString(": ")+ .ifBlank { accountEmail }+ }+ } else {+ count = ordered.size+ latestWhen = ordered.maxOfOrNull { it.dateMillis }?.takeIf { it > 0L }+ ?: System.currentTimeMillis()+ lines = ordered.asReversed().map { msg ->+ val sender = msg.from.substringBefore("<").trim().ifEmpty { msg.from }+ "$sender: ${msg.subject.ifBlank { "(no subject)" }}"+ }+ }++ val title = if (count == 1) "1 new message" else "$count new messages"+ val style = NotificationCompat.InboxStyle()+ .setBigContentTitle(title)+ .setSummaryText(accountEmail)+ for (line in lines) style.addLine(line)++ // Summary tap opens the app (account inbox, no specific thread).+ val launch = Intent(context, MainActivity::class.java).apply {+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)+ putExtra("accountEmail", accountEmail)+ }+ val pi = PendingIntent.getActivity(+ context,+ summaryNotificationId(accountEmail),+ launch,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+ return NotificationCompat.Builder(context, channelId(accountEmail))+ .setSmallIcon(R.drawable.ic_notification_mail)+ .setContentTitle(title)+ .setContentText(accountEmail)+ .setSubText(accountEmail)+ .setWhen(latestWhen)+ .setShowWhen(true)+ .setNumber(count)+ .setStyle(style)+ .setGroup(groupKey(accountEmail))+ .setGroupSummary(true)+ .setAutoCancel(true)+ .setContentIntent(pi)+ .build()+ }+ private fun postOne( nm: NotificationManagerCompat, context: Context,@@ -153,6 +291,7 @@ object EmailNotifications { } ) )+ .setGroup(groupKey(accountEmail)) .setAutoCancel(true) .setContentIntent(pi) .build()
email/src/test/java/com/vayunmathur/email/platform/EmailNotificationsTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/platform/EmailNotificationsTest.kt b/email/src/test/java/com/vayunmathur/email/platform/EmailNotificationsTest.ktindex 805cedd232..0c335311e6 100644--- a/email/src/test/java/com/vayunmathur/email/platform/EmailNotificationsTest.kt+++ b/email/src/test/java/com/vayunmathur/email/platform/EmailNotificationsTest.kt@@ -42,9 +42,70 @@ class EmailNotificationsTest { ) val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val posted = Shadows.shadowOf(nm).allNotifications- assertEquals(2, posted.size)+ // Two children plus the one per-account group summary.+ assertEquals(3, posted.size) assertTrue(posted.all { it.channelId == "new_mail::[email protected]" })- val titles = posted.map { it.extras.getCharSequence("android.title")?.toString() }+ val children = posted.filter {+ (it.flags and android.app.Notification.FLAG_GROUP_SUMMARY) == 0+ }+ assertEquals(2, children.size)+ val titles = children.map { it.extras.getCharSequence("android.title")?.toString() } assertTrue(titles.all { it == "Sender" }) }++ @Test+ fun `children are grouped per account with one InboxStyle summary`() {+ EmailNotifications.postForNewMessages(+ context, "[email protected]",+ listOf(message(2L, 2000L), message(1L, 1000L)),+ )+ // A second batch for the same account must not add a second summary.+ EmailNotifications.postForNewMessages(context, "[email protected]", listOf(message(3L, 3000L)))++ val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ val active = nm.activeNotifications.toList()+ val summaries = active.filter {+ (it.notification.flags and android.app.Notification.FLAG_GROUP_SUMMARY) != 0+ }+ val children = active.filter {+ (it.notification.flags and android.app.Notification.FLAG_GROUP_SUMMARY) == 0+ }+ assertEquals(1, summaries.size)+ assertEquals(3, children.size)+ assertTrue(active.all { it.notification.group == "[email protected]" })+ assertTrue(children.none { it.id == summaries.single().id })++ val summary = summaries.single().notification+ assertEquals("new_mail::[email protected]", summary.channelId)+ val lines = summary.extras.getCharSequenceArray("android.textLines").orEmpty()+ assertEquals(3, lines.size)+ assertTrue(lines.any { it.toString().contains("Subject 3") })+ // Summary tap opens the app.+ val launch = Shadows.shadowOf(summary.contentIntent).savedIntent+ assertEquals(+ com.vayunmathur.email.MainActivity::class.java.name,+ launch.component?.className,+ )+ }++ @Test+ fun `cancelForMessages keeps child ids and drops summary only when group empties`() {+ val first = message(1L, 1000L)+ val second = message(2L, 2000L)+ EmailNotifications.postForNewMessages(context, "[email protected]", listOf(first, second))+ val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ assertEquals(3, nm.activeNotifications.size)++ EmailNotifications.cancelForMessages(context, listOf(first))+ // One child + the summary remain.+ assertEquals(2, nm.activeNotifications.size)+ assertTrue(+ nm.activeNotifications.any {+ (it.notification.flags and android.app.Notification.FLAG_GROUP_SUMMARY) != 0+ },+ )++ EmailNotifications.cancelForMessages(context, listOf(second))+ assertTrue(nm.activeNotifications.isEmpty())+ } }