TypeScript
fix(mobile): show one Android notification per thread completion (#27699)
shivam81922e68d49b
diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.ktindex f9b69a71177..9d4f69bb79e 100644--- a/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt+++ b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt@@ -127,8 +127,8 @@ object AgentNotifications {if (registered && fresh && NotificationManagerCompat.from(context).areNotificationsEnabled()) {channels(context)val scheme = prefs.getString("scheme", "t3code") ?: "t3code"- showAlert(context, prefs, scheme, data)- updateActivity(context, prefs, scheme, data, updatedAt)+ val alerted = showAlert(context, prefs, scheme, data)+ updateActivity(context, prefs, data, updatedAt, alerted)}}@@ -137,7 +137,7 @@ object AgentNotifications {prefs: SharedPreferences,scheme: String,data: Map<String, String>- ) {+ ): Boolean {// Queue retries carry the same alert id. Keep a bounded history even when// notification A is retried after notification B has already arrived.val alertId = data["alert_id"]@@ -157,7 +157,14 @@ object AgentNotifications {"seenAlertsOrdered",(seen.takeLast(63) + alertId).joinToString("\n")).apply()+ // Android drops posts to a blocked channel, so that alert shows nothing.+ return !onScreen && (+ Build.VERSION.SDK_INT < 26 ||+ manager(context).getNotificationChannel(ALERT_CHANNEL)?.importance !=+ NotificationManager.IMPORTANCE_NONE+ )}+ return false}private fun postAlert(@@ -215,12 +222,21 @@ object AgentNotifications {private fun updateActivity(context: Context,prefs: SharedPreferences,- scheme: String,data: Map<String, String>,- updatedAt: Long+ updatedAt: Long,+ alerted: Boolean) {- if (updatedAt < prefs.getLong("lastUpdate", 0)) return- prefs.edit().putLong("lastUpdate", updatedAt).apply()+ val terminal = singleTerminal(data)+ // Only a one-row card on the alert's own thread is known to show nothing more+ // than the alert. Grouped alerts and cards with other rows stay visible.+ val covered = terminal?.takeIf { alerted && data["alert_path"] == data["activity_path"] }+ if (covered != null) coverTerminal(prefs, covered, updatedAt)+ if (updatedAt < prefs.getLong("lastUpdate", 0)) {+ // A newer replay of this same finish may already show the card.+ if (isCovered(prefs, prefs.getString("lastTerminal", null))) cancelActivity(context)+ return+ }+ prefs.edit().putLong("lastUpdate", updatedAt).putString("lastTerminal", terminal).apply()val active = data["active"] == "true"// Use absolute state expiry: a replay must not extend a finished card or// make an abandoned host look active indefinitely. Older relays omit it.@@ -237,11 +253,35 @@ object AgentNotifications {// Dismissing a run includes its finished card. A new run, or toggling// activity off/on, arms it again; terminal replays stay dismissed.if (active && !wasActive) prefs.edit().putBoolean("dismissed", false).apply()- if (!prefs.getBoolean("dismissed", false)) {+ if (prefs.getBoolean("dismissed", false) || isCovered(prefs, terminal)) {+ cancelActivity(context)+ } else {+ val scheme = prefs.getString("scheme", "t3code") ?: "t3code"showActivity(context, scheme, data, active, remainingMs)}}+ /** Identifies a finished one-thread card by its path, phase and absolute expiry. */+ private fun singleTerminal(data: Map<String, String>): String? {+ val phase = data["activity_phase"]+ val finished = phase == "completed" || phase == "failed"+ val single = data.containsKey("activity_line_0") && !data.containsKey("activity_line_1")+ val expiresAt = data["activity_expires_at"]+ return "${data["activity_path"]}\n$phase\n$expiresAt"+ .takeIf { finished && single && expiresAt != null }+ }++ private fun isCovered(prefs: SharedPreferences, terminal: String?) =+ terminal != null && terminal == prefs.getString("coveredTerminal", null)++ private fun coverTerminal(prefs: SharedPreferences, terminal: String?, updatedAt: Long) {+ if (updatedAt >= prefs.getLong("lastUpdate", 0) ||+ prefs.getString("lastTerminal", null) == terminal+ ) {+ prefs.edit().putString("coveredTerminal", terminal).apply()+ }+ }+private fun showActivity(context: Context,scheme: String,diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt b/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.ktindex 7ca6edbc213..59ab4d6651e 100644--- a/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt+++ b/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt@@ -24,12 +24,10 @@ import org.robolectric.RuntimeEnvironmentimport org.robolectric.Shadows.shadowOfimport org.robolectric.annotation.Config-@RunWith(RobolectricTestRunner::class)-@Config(sdk = [24, 26, 33, 36], manifest = Config.NONE)-class AgentNotificationsTest {- private lateinit var context: Application- private lateinit var manager: NotificationManager- private lateinit var lifecycle: LifecycleRegistry+abstract class AgentNotificationsFixture {+ protected lateinit var context: Application+ protected lateinit var manager: NotificationManager+ protected lateinit var lifecycle: LifecycleRegistry@Beforefun setUp() {@@ -52,7 +50,7 @@ class AgentNotificationsTest {AgentNotifications.setThreadOnScreen("/threads/environment/thread")}- private fun update(alertId: String, active: Boolean) = mapOf(+ protected fun update(alertId: String, active: Boolean) = mapOf("device_id" to "device","user_id" to "user","updated_at" to System.currentTimeMillis().toString(),@@ -66,7 +64,11 @@ class AgentNotificationsTest {"alert_body" to "Done: Test project","alert_path" to "/threads/environment/thread",)+}+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [24, 26, 33, 36], manifest = Config.NONE)+class AgentNotificationsTest : AgentNotificationsFixture() {@Testfun alertHistoryEvictsOnlyTheOldestEntryAfterCapacity() {lifecycle.currentState = Lifecycle.State.RESUMED@@ -118,20 +120,6 @@ class AgentNotificationsTest {assertTrue(manager.activeNotifications.isEmpty())}- @Test- fun backgroundCompletionAlertsAndClearsOngoingActivity() {- lifecycle.currentState = Lifecycle.State.RESUMED- AgentNotifications.receive(context, update("running", true))- lifecycle.currentState = Lifecycle.State.CREATED-- AgentNotifications.receive(context, update("completion", false))-- val alert = manager.activeNotifications.single()- assertEquals("t3-agent-alert", alert.tag)- assertEquals("Test thread", alert.notification.extras.getString(Notification.EXTRA_TITLE))- assertFalse(alert.notification.flags and Notification.FLAG_ONGOING_EVENT != 0)- }-@Testfun retryOfForegroundSuppressedAlertDoesNotAppearAfterBackgrounding() {lifecycle.currentState = Lifecycle.State.RESUMED@@ -313,21 +301,6 @@ class AgentNotificationsTest {assertTrue(manager.activeNotifications.isEmpty())}- @Test- fun reorderedActivityDoesNotEraseNewerCardOrDropAnIndependentAlert() {- val now = System.currentTimeMillis()- AgentNotifications.receive(context, update("new", true) + ("updated_at" to now.toString()))- AgentNotifications.receive(- context,- update("older-alert", false) + ("updated_at" to (now - 1000).toString())- )- assertEquals(4, manager.activeNotifications.size)- assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })- shadowOf(manager).setNotificationsEnabled(false)- AgentNotifications.receive(context, update("revoked-permission", true))- assertEquals(4, manager.activeNotifications.size)- }-@Testfun severalThreadsListEveryRowWithItsStatusAndActionsFollowThePriorityThread() {lifecycle.currentState = Lifecycle.State.RESUMED@@ -661,3 +634,91 @@ class AgentNotificationsTest {assertEquals(2, manager.activeNotifications.size)}}++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [24, 26, 33, 36], manifest = Config.NONE)+class AgentNotificationsCompletionTest : AgentNotificationsFixture() {+ private fun finished(alertId: String, expiresAt: Long) = update(alertId, false) + mapOf(+ "activity_line_0" to "Done\tTest thread\tTest project",+ "activity_phase" to "completed",+ "activity_expires_at" to expiresAt.toString(),+ )++ @Test+ fun backgroundCompletionAlertsAndClearsOngoingActivity() {+ lifecycle.currentState = Lifecycle.State.RESUMED+ AgentNotifications.receive(context, update("running", true))+ lifecycle.currentState = Lifecycle.State.CREATED++ val expiresAt = System.currentTimeMillis() + 900000+ val completion = finished("completion", expiresAt)+ AgentNotifications.receive(context, completion)+ AgentNotifications.receive(context, completion)+ AgentNotifications.receive(context, completion.filterKeys { !it.startsWith("alert_") })++ val alert = manager.activeNotifications.single()+ assertEquals("t3-agent-alert", alert.tag)+ assertEquals("Test thread", alert.notification.extras.getString(Notification.EXTRA_TITLE))+ assertFalse(alert.notification.flags and Notification.FLAG_ONGOING_EVENT != 0)+ AgentNotifications.receive(context, update("next-run", true))+ assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })++ // An alert for another thread, or a card that also lists another result, stays.+ AgentNotifications.receive(+ context,+ finished("other-thread", expiresAt + 60000) + ("alert_path" to "/threads/other/thread")+ )+ assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })+ AgentNotifications.receive(+ context,+ finished("with-muted-result", expiresAt + 120000) ++ ("activity_line_1" to "Done\tMuted thread\tOther project")+ )+ assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })+ }++ @Test+ @Config(sdk = [26, 33, 36])+ fun blockedAlertChannelKeepsTheFinishedCard() {+ manager.getNotificationChannel("agent-alerts").importance = NotificationManager.IMPORTANCE_NONE+ AgentNotifications.receive(+ context,+ finished("completion", System.currentTimeMillis() + 900000)+ )+ assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })+ }++ @Test+ fun reorderedActivityDoesNotEraseNewerCardOrDropAnIndependentAlert() {+ val now = System.currentTimeMillis()+ AgentNotifications.receive(context, update("new", true) + ("updated_at" to now.toString()))+ AgentNotifications.receive(+ context,+ finished("older-alert", now + 900000) + ("updated_at" to (now - 1000).toString())+ )+ assertEquals(4, manager.activeNotifications.size)+ assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })+ // A newer replay of a finish can show its card before the original alert lands.+ val finish = finished("finish", now + 960000)+ AgentNotifications.receive(+ context,+ finish.filterKeys { !it.startsWith("alert_") } + ("updated_at" to (now + 2000).toString())+ )+ assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })+ AgentNotifications.receive(context, finish + ("updated_at" to (now + 1000).toString()))+ assertTrue(manager.activeNotifications.none { it.tag == "t3-agent-activity" })+ assertTrue(manager.activeNotifications.any { it.id == "finish".hashCode() })+ AgentNotifications.receive(+ context,+ finished("previous-run", now + 900000) + ("updated_at" to now.toString())+ )+ AgentNotifications.receive(+ context,+ finish.filterKeys { !it.startsWith("alert_") } + ("updated_at" to (now + 3000).toString())+ )+ assertTrue(manager.activeNotifications.none { it.tag == "t3-agent-activity" })+ shadowOf(manager).setNotificationsEnabled(false)+ AgentNotifications.receive(context, update("revoked-permission", true))+ assertEquals(5, manager.activeNotifications.size)+ }+}