@devries-cameron20 / t3code Mirror · read-only / commits / 81922e68d4
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 03:15 UTC

fix(mobile): show one Android notification per thread completion (#27699)

Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

shivam committed Nov 6, 2026 at 06:18 UTC 81922e68d49b5265e82d64d029e25a103bf5f620
2 files changed +145 -44
apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt
+48 -8
@@ -127,8 +127,8 @@ object AgentNotifications {
127 if (registered && fresh && NotificationManagerCompat.from(context).areNotificationsEnabled()) {
128 channels(context)
129 val scheme = prefs.getString("scheme", "t3code") ?: "t3code"
130 - showAlert(context, prefs, scheme, data)
131 - updateActivity(context, prefs, scheme, data, updatedAt)
130 + val alerted = showAlert(context, prefs, scheme, data)
131 + updateActivity(context, prefs, data, updatedAt, alerted)
132 }
133 }
134
@@ -137,7 +137,7 @@ object AgentNotifications {
137 prefs: SharedPreferences,
138 scheme: String,
139 data: Map<String, String>
140 - ) {
140 + ): Boolean {
141 // Queue retries carry the same alert id. Keep a bounded history even when
142 // notification A is retried after notification B has already arrived.
143 val alertId = data["alert_id"]
@@ -157,7 +157,14 @@ object AgentNotifications {
157 "seenAlertsOrdered",
158 (seen.takeLast(63) + alertId).joinToString("\n")
159 ).apply()
160 + // Android drops posts to a blocked channel, so that alert shows nothing.
161 + return !onScreen && (
162 + Build.VERSION.SDK_INT < 26 ||
163 + manager(context).getNotificationChannel(ALERT_CHANNEL)?.importance !=
164 + NotificationManager.IMPORTANCE_NONE
165 + )
166 }
167 + return false
168 }
169
170 private fun postAlert(
@@ -215,12 +222,21 @@ object AgentNotifications {
222 private fun updateActivity(
223 context: Context,
224 prefs: SharedPreferences,
218 - scheme: String,
225 data: Map<String, String>,
220 - updatedAt: Long
226 + updatedAt: Long,
227 + alerted: Boolean
228 ) {
222 - if (updatedAt < prefs.getLong("lastUpdate", 0)) return
223 - prefs.edit().putLong("lastUpdate", updatedAt).apply()
229 + val terminal = singleTerminal(data)
230 + // Only a one-row card on the alert's own thread is known to show nothing more
231 + // than the alert. Grouped alerts and cards with other rows stay visible.
232 + val covered = terminal?.takeIf { alerted && data["alert_path"] == data["activity_path"] }
233 + if (covered != null) coverTerminal(prefs, covered, updatedAt)
234 + if (updatedAt < prefs.getLong("lastUpdate", 0)) {
235 + // A newer replay of this same finish may already show the card.
236 + if (isCovered(prefs, prefs.getString("lastTerminal", null))) cancelActivity(context)
237 + return
238 + }
239 + prefs.edit().putLong("lastUpdate", updatedAt).putString("lastTerminal", terminal).apply()
240 val active = data["active"] == "true"
241 // Use absolute state expiry: a replay must not extend a finished card or
242 // make an abandoned host look active indefinitely. Older relays omit it.
@@ -237,11 +253,35 @@ object AgentNotifications {
253 // Dismissing a run includes its finished card. A new run, or toggling
254 // activity off/on, arms it again; terminal replays stay dismissed.
255 if (active && !wasActive) prefs.edit().putBoolean("dismissed", false).apply()
240 - if (!prefs.getBoolean("dismissed", false)) {
256 + if (prefs.getBoolean("dismissed", false) || isCovered(prefs, terminal)) {
257 + cancelActivity(context)
258 + } else {
259 + val scheme = prefs.getString("scheme", "t3code") ?: "t3code"
260 showActivity(context, scheme, data, active, remainingMs)
261 }
262 }
263
264 + /** Identifies a finished one-thread card by its path, phase and absolute expiry. */
265 + private fun singleTerminal(data: Map<String, String>): String? {
266 + val phase = data["activity_phase"]
267 + val finished = phase == "completed" || phase == "failed"
268 + val single = data.containsKey("activity_line_0") && !data.containsKey("activity_line_1")
269 + val expiresAt = data["activity_expires_at"]
270 + return "${data["activity_path"]}\n$phase\n$expiresAt"
271 + .takeIf { finished && single && expiresAt != null }
272 + }
273 +
274 + private fun isCovered(prefs: SharedPreferences, terminal: String?) =
275 + terminal != null && terminal == prefs.getString("coveredTerminal", null)
276 +
277 + private fun coverTerminal(prefs: SharedPreferences, terminal: String?, updatedAt: Long) {
278 + if (updatedAt >= prefs.getLong("lastUpdate", 0) ||
279 + prefs.getString("lastTerminal", null) == terminal
280 + ) {
281 + prefs.edit().putString("coveredTerminal", terminal).apply()
282 + }
283 + }
284 +
285 private fun showActivity(
286 context: Context,
287 scheme: String,
apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt
+97 -36
@@ -24,12 +24,10 @@ import org.robolectric.RuntimeEnvironment
24 import org.robolectric.Shadows.shadowOf
25 import org.robolectric.annotation.Config
26
27 -@RunWith(RobolectricTestRunner::class)
28 -@Config(sdk = [24, 26, 33, 36], manifest = Config.NONE)
29 -class AgentNotificationsTest {
30 - private lateinit var context: Application
31 - private lateinit var manager: NotificationManager
32 - private lateinit var lifecycle: LifecycleRegistry
27 +abstract class AgentNotificationsFixture {
28 + protected lateinit var context: Application
29 + protected lateinit var manager: NotificationManager
30 + protected lateinit var lifecycle: LifecycleRegistry
31
32 @Before
33 fun setUp() {
@@ -52,7 +50,7 @@ class AgentNotificationsTest {
50 AgentNotifications.setThreadOnScreen("/threads/environment/thread")
51 }
52
55 - private fun update(alertId: String, active: Boolean) = mapOf(
53 + protected fun update(alertId: String, active: Boolean) = mapOf(
54 "device_id" to "device",
55 "user_id" to "user",
56 "updated_at" to System.currentTimeMillis().toString(),
@@ -66,7 +64,11 @@ class AgentNotificationsTest {
64 "alert_body" to "Done: Test project",
65 "alert_path" to "/threads/environment/thread",
66 )
67 +}
68
69 +@RunWith(RobolectricTestRunner::class)
70 +@Config(sdk = [24, 26, 33, 36], manifest = Config.NONE)
71 +class AgentNotificationsTest : AgentNotificationsFixture() {
72 @Test
73 fun alertHistoryEvictsOnlyTheOldestEntryAfterCapacity() {
74 lifecycle.currentState = Lifecycle.State.RESUMED
@@ -118,20 +120,6 @@ class AgentNotificationsTest {
120 assertTrue(manager.activeNotifications.isEmpty())
121 }
122
121 - @Test
122 - fun backgroundCompletionAlertsAndClearsOngoingActivity() {
123 - lifecycle.currentState = Lifecycle.State.RESUMED
124 - AgentNotifications.receive(context, update("running", true))
125 - lifecycle.currentState = Lifecycle.State.CREATED
126 -
127 - AgentNotifications.receive(context, update("completion", false))
128 -
129 - val alert = manager.activeNotifications.single()
130 - assertEquals("t3-agent-alert", alert.tag)
131 - assertEquals("Test thread", alert.notification.extras.getString(Notification.EXTRA_TITLE))
132 - assertFalse(alert.notification.flags and Notification.FLAG_ONGOING_EVENT != 0)
133 - }
134 -
123 @Test
124 fun retryOfForegroundSuppressedAlertDoesNotAppearAfterBackgrounding() {
125 lifecycle.currentState = Lifecycle.State.RESUMED
@@ -313,21 +301,6 @@ class AgentNotificationsTest {
301 assertTrue(manager.activeNotifications.isEmpty())
302 }
303
316 - @Test
317 - fun reorderedActivityDoesNotEraseNewerCardOrDropAnIndependentAlert() {
318 - val now = System.currentTimeMillis()
319 - AgentNotifications.receive(context, update("new", true) + ("updated_at" to now.toString()))
320 - AgentNotifications.receive(
321 - context,
322 - update("older-alert", false) + ("updated_at" to (now - 1000).toString())
323 - )
324 - assertEquals(4, manager.activeNotifications.size)
325 - assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })
326 - shadowOf(manager).setNotificationsEnabled(false)
327 - AgentNotifications.receive(context, update("revoked-permission", true))
328 - assertEquals(4, manager.activeNotifications.size)
329 - }
330 -
304 @Test
305 fun severalThreadsListEveryRowWithItsStatusAndActionsFollowThePriorityThread() {
306 lifecycle.currentState = Lifecycle.State.RESUMED
@@ -661,3 +634,91 @@ class AgentNotificationsTest {
634 assertEquals(2, manager.activeNotifications.size)
635 }
636 }
637 +
638 +@RunWith(RobolectricTestRunner::class)
639 +@Config(sdk = [24, 26, 33, 36], manifest = Config.NONE)
640 +class AgentNotificationsCompletionTest : AgentNotificationsFixture() {
641 + private fun finished(alertId: String, expiresAt: Long) = update(alertId, false) + mapOf(
642 + "activity_line_0" to "Done\tTest thread\tTest project",
643 + "activity_phase" to "completed",
644 + "activity_expires_at" to expiresAt.toString(),
645 + )
646 +
647 + @Test
648 + fun backgroundCompletionAlertsAndClearsOngoingActivity() {
649 + lifecycle.currentState = Lifecycle.State.RESUMED
650 + AgentNotifications.receive(context, update("running", true))
651 + lifecycle.currentState = Lifecycle.State.CREATED
652 +
653 + val expiresAt = System.currentTimeMillis() + 900000
654 + val completion = finished("completion", expiresAt)
655 + AgentNotifications.receive(context, completion)
656 + AgentNotifications.receive(context, completion)
657 + AgentNotifications.receive(context, completion.filterKeys { !it.startsWith("alert_") })
658 +
659 + val alert = manager.activeNotifications.single()
660 + assertEquals("t3-agent-alert", alert.tag)
661 + assertEquals("Test thread", alert.notification.extras.getString(Notification.EXTRA_TITLE))
662 + assertFalse(alert.notification.flags and Notification.FLAG_ONGOING_EVENT != 0)
663 + AgentNotifications.receive(context, update("next-run", true))
664 + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })
665 +
666 + // An alert for another thread, or a card that also lists another result, stays.
667 + AgentNotifications.receive(
668 + context,
669 + finished("other-thread", expiresAt + 60000) + ("alert_path" to "/threads/other/thread")
670 + )
671 + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })
672 + AgentNotifications.receive(
673 + context,
674 + finished("with-muted-result", expiresAt + 120000) +
675 + ("activity_line_1" to "Done\tMuted thread\tOther project")
676 + )
677 + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })
678 + }
679 +
680 + @Test
681 + @Config(sdk = [26, 33, 36])
682 + fun blockedAlertChannelKeepsTheFinishedCard() {
683 + manager.getNotificationChannel("agent-alerts").importance = NotificationManager.IMPORTANCE_NONE
684 + AgentNotifications.receive(
685 + context,
686 + finished("completion", System.currentTimeMillis() + 900000)
687 + )
688 + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })
689 + }
690 +
691 + @Test
692 + fun reorderedActivityDoesNotEraseNewerCardOrDropAnIndependentAlert() {
693 + val now = System.currentTimeMillis()
694 + AgentNotifications.receive(context, update("new", true) + ("updated_at" to now.toString()))
695 + AgentNotifications.receive(
696 + context,
697 + finished("older-alert", now + 900000) + ("updated_at" to (now - 1000).toString())
698 + )
699 + assertEquals(4, manager.activeNotifications.size)
700 + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })
701 + // A newer replay of a finish can show its card before the original alert lands.
702 + val finish = finished("finish", now + 960000)
703 + AgentNotifications.receive(
704 + context,
705 + finish.filterKeys { !it.startsWith("alert_") } + ("updated_at" to (now + 2000).toString())
706 + )
707 + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" })
708 + AgentNotifications.receive(context, finish + ("updated_at" to (now + 1000).toString()))
709 + assertTrue(manager.activeNotifications.none { it.tag == "t3-agent-activity" })
710 + assertTrue(manager.activeNotifications.any { it.id == "finish".hashCode() })
711 + AgentNotifications.receive(
712 + context,
713 + finished("previous-run", now + 900000) + ("updated_at" to now.toString())
714 + )
715 + AgentNotifications.receive(
716 + context,
717 + finish.filterKeys { !it.startsWith("alert_") } + ("updated_at" to (now + 3000).toString())
718 + )
719 + assertTrue(manager.activeNotifications.none { it.tag == "t3-agent-activity" })
720 + shadowOf(manager).setNotificationsEnabled(false)
721 + AgentNotifications.receive(context, update("revoked-permission", true))
722 + assertEquals(5, manager.activeNotifications.size)
723 + }
724 +}