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.kt index 220ba4a75be51..33fbb9e328c8b 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 @@ -98,6 +98,32 @@ object AgentNotifications { threadOnScreen = path } + @Synchronized + fun setThreadOnScreen(context: Context, path: String?) { + threadOnScreen = path + if (path != null) { + val prefs = context.getSharedPreferences(STORE, Context.MODE_PRIVATE) + val lastTerminal = prefs + .takeUnless { it.getBoolean("lastActive", false) } + ?.getString("lastTerminal", null) + val matchesSingleRow = lastTerminal?.split('\n')?.let { + it.size == 4 && it[0] == path && it[3] == "true" + } == true + if (matchesSingleRow) { + prefs.edit().putString("coveredTerminal", lastTerminal).apply() + cancelActivity(context) + } + } + } + + private fun isThreadOnScreen(path: String?): Boolean { + val resumed = ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast( + Lifecycle.State.RESUMED + ) + val visibleThread = threadOnScreen + return resumed && visibleThread != null && path == visibleThread + } + @Synchronized fun dismiss(context: Context) { context.getSharedPreferences( @@ -154,11 +180,7 @@ object AgentNotifications { ?: prefs.getStringSet("seenAlerts", emptySet()).orEmpty().toList() if (alertId != null && alertId !in seen) { // Consume suppressed alerts so retries cannot resurface them later. - val resumed = ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast( - Lifecycle.State.RESUMED - ) - val visibleThread = threadOnScreen - val onScreen = resumed && visibleThread != null && data["alert_path"] == visibleThread + val onScreen = isThreadOnScreen(data["alert_path"]) if (!onScreen) { postAlert(context, scheme, data, alertId) } @@ -235,10 +257,10 @@ object AgentNotifications { updatedAt: Long, alerted: Boolean ) { - 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"] } + val terminal = terminalKey(data) + // Hide a finished card when its alert already covered the visible rows or the + // user is already looking at the finished thread on screen. + val covered = coveredTerminal(data, terminal, alerted) 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. @@ -270,14 +292,34 @@ object AgentNotifications { } } - /** Identifies a finished one-thread card by its path, phase and absolute expiry. */ - private fun singleTerminal(data: Map): String? { + private fun coveredTerminal( + data: Map, + terminal: String?, + alerted: Boolean + ): String? = terminal?.takeIf { + val singleRow = data.containsKey("activity_line_0") && !data.containsKey("activity_line_1") + if (singleRow) { + (alerted && data["alert_path"] == data["activity_path"]) || + isThreadOnScreen(data["activity_path"]) + } else { + alerted && data["alert_path"] == "/" && data["alert_covers_activity"] == "true" + } + } + + /** Identifies a finished card by its path, phase, rows and absolute expiry. */ + private fun terminalKey(data: Map): String? { + if (data["active"] == "true") return null val phase = data["activity_phase"] val finished = phase == "completed" || phase == "failed" - val single = data.containsKey("activity_line_0") && !data.containsKey("activity_line_1") + val rows = generateSequence(0) { it + 1 } + .map { data["activity_line_$it"] } + .takeWhile { it != null } + .filterNotNull() + .toList() val expiresAt = data["activity_expires_at"] - return "${data["activity_path"]}\n$phase\n$expiresAt" - .takeIf { finished && single && expiresAt != null } + val scope = if (rows.size == 1) "true" else "false\n${rows.joinToString("\n")}" + return "${data["activity_path"]}\n$phase\n$expiresAt\n$scope" + .takeIf { finished && rows.isNotEmpty() && expiresAt != null } } private fun isCovered(prefs: SharedPreferences, terminal: String?) = diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/T3AgentNotificationsModule.kt b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/T3AgentNotificationsModule.kt index cbef915cb7dad..d49b954b5a1b1 100644 --- a/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/T3AgentNotificationsModule.kt +++ b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/T3AgentNotificationsModule.kt @@ -31,7 +31,12 @@ class T3AgentNotificationsModule : Module() { } Function("setThreadOnScreen") { path: String? -> - AgentNotifications.setThreadOnScreen(path) + val context = appContext.reactContext + if (context != null) { + AgentNotifications.setThreadOnScreen(context, path) + } else { + AgentNotifications.setThreadOnScreen(path) + } } Function("openLiveUpdateSettings") { 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.kt index eb054f4d484fe..697364c9be32f 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 @@ -381,6 +381,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() { "activity_phase" to "running", ) AgentNotifications.receive(context, data) + AgentNotifications.setThreadOnScreen("/threads/environment/other") val working = manager.activeNotifications.single().notification assertEquals( "Update dashboard", @@ -824,4 +825,85 @@ class AgentNotificationsCompletionTest : AgentNotificationsFixture() { AgentNotifications.receive(context, update("revoked-permission", true)) assertEquals(5, manager.activeNotifications.size) } + + @Test + fun foregroundOnScreenCompletionHidesFinishedActivityAndStaysHiddenOnReplay() { + lifecycle.currentState = Lifecycle.State.RESUMED + AgentNotifications.receive(context, update("running", true)) + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" }) + + val completion = finished("on-screen-done", System.currentTimeMillis() + 900000) + AgentNotifications.receive(context, completion) + assertTrue(manager.activeNotifications.isEmpty()) + + lifecycle.currentState = Lifecycle.State.CREATED + AgentNotifications.receive(context, completion.filterKeys { !it.startsWith("alert_") }) + assertTrue(manager.activeNotifications.isEmpty()) + } + + @Test + fun viewingFinishedThreadClearsRetainedActivityWithoutClearingActiveWork() { + val expiresAt = System.currentTimeMillis() + 900000 + AgentNotifications.receive(context, update("running", true)) + AgentNotifications.setThreadOnScreen(context, "/threads/environment/thread") + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" }) + + AgentNotifications.setThreadOnScreen(context, null) + val completion = finished("retained", expiresAt).filterKeys { !it.startsWith("alert_") } + AgentNotifications.receive(context, completion) + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" }) + + AgentNotifications.setThreadOnScreen(context, "/threads/environment/thread") + assertTrue(manager.activeNotifications.none { it.tag == "t3-agent-activity" }) + + // Replaying the same completion after viewing must not restore the card. + AgentNotifications.setThreadOnScreen(context, null) + AgentNotifications.receive(context, completion) + assertTrue(manager.activeNotifications.none { it.tag == "t3-agent-activity" }) + + // Viewing one thread does not clear a multi-row finished card with another result. + val multiRow = finished("multi-retained", expiresAt + 60000) + .filterKeys { !it.startsWith("alert_") } + + ("activity_line_1" to "Done\tMuted thread\tOther project") + AgentNotifications.receive(context, multiRow) + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" }) + AgentNotifications.setThreadOnScreen(context, "/threads/environment/thread") + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" }) + } + + @Test + fun groupedCompletionAlertHidesFinishedMultiRowActivity() { + val expiresAt = System.currentTimeMillis() + 900000 + val partialGrouped = finished("grouped-partial", expiresAt) + mapOf( + "activity_line_1" to "Done\tMuted thread\tOther project", + "alert_title" to "2 agents finished", + "alert_body" to "Test thread, Second thread", + "alert_path" to "/", + ) + // A grouped alert without full-card coverage leaves the multi-row finished card visible. + AgentNotifications.receive(context, partialGrouped) + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" }) + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-alert" }) + + val coveredGrouped = finished("grouped-done", expiresAt + 60000) + mapOf( + "activity_line_1" to "Done\tSecond thread\tOther project", + "alert_title" to "2 agents finished", + "alert_body" to "Test thread, Second thread", + "alert_path" to "/", + "alert_covers_activity" to "true", + ) + AgentNotifications.receive(context, coveredGrouped) + assertTrue(manager.activeNotifications.none { it.tag == "t3-agent-activity" }) + assertTrue(manager.activeNotifications.any { it.id == "grouped-done".hashCode() }) + + AgentNotifications.receive(context, coveredGrouped.filterKeys { !it.startsWith("alert_") }) + assertTrue(manager.activeNotifications.none { it.tag == "t3-agent-activity" }) + + // A later multi-row finished card with the same hero row and expiry but a different + // second row must not reuse the covered terminal key. + val differentRows = coveredGrouped.filterKeys { !it.startsWith("alert_") } + + ("activity_line_1" to "Done\tThird thread\tThird project") + AgentNotifications.receive(context, differentRows) + assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" }) + } } diff --git a/infra/relay/src/agentActivity/FcmDeliveries.test.ts b/infra/relay/src/agentActivity/FcmDeliveries.test.ts index d6ed7ec687ffe..368642448f179 100644 --- a/infra/relay/src/agentActivity/FcmDeliveries.test.ts +++ b/infra/relay/src/agentActivity/FcmDeliveries.test.ts @@ -246,11 +246,47 @@ describe("Android delivery routing", () => { alert_path: "/", active, }); + expect(alerts[0]?.data.alert_covers_activity).toBe(active === "false" ? "true" : undefined); expect(h.marked.at(-1)?.aggregate?.activities).toHaveLength(2); }).pipe(Effect.provide(h.layer)); }, ); + it.effect( + "does not mark a grouped completion alert as covering rows from muted environments", + () => { + const h = harness(); + const mutedState: RelayAgentActivityState = { + ...state, + environmentId: EnvironmentId.make("muted-env"), + threadId: ThreadId.make("muted-thread"), + threadTitle: "Muted thread", + deepLink: "/threads/muted-env/muted-thread", + }; + h.current.mutedEnvironments = [mutedState.environmentId]; + h.current.otherStates = [secondState, mutedState]; + return Effect.gen(function* () { + const delivery = yield* FcmDeliveries.FcmDeliveries; + yield* delivery.process(h.job); + h.current.state = { ...state, phase: "completed" }; + h.current.otherStates = [ + { ...secondState, phase: "completed" }, + { ...mutedState, phase: "completed" }, + ]; + yield* delivery.process({ ...h.job, state: h.current.state }); + const alerts = h.sent.filter((message) => message.alert); + expect(alerts).toHaveLength(1); + expect(alerts[0]?.data).toMatchObject({ + alert_title: "2 agents finished", + alert_body: "Fix notifications, Second thread", + alert_path: "/", + active: "false", + }); + expect(alerts[0]?.data.alert_covers_activity).toBeUndefined(); + }).pipe(Effect.provide(h.layer)); + }, + ); + it.effect("filters disabled event types before counting a group", () => { const h = harness(); h.current.target.last_aggregate_json = encodeJson(aggregateFor([state, secondState])); diff --git a/infra/relay/src/agentActivity/FcmDeliveries.ts b/infra/relay/src/agentActivity/FcmDeliveries.ts index 501976523b283..a615bcfe0fdca 100644 --- a/infra/relay/src/agentActivity/FcmDeliveries.ts +++ b/infra/relay/src/agentActivity/FcmDeliveries.ts @@ -1,5 +1,6 @@ import { and, eq } from "drizzle-orm"; import { + type RelayAgentActivityAggregateRow, RelayAgentActivityState, RelayAgentActivityAggregateState, RelayAgentAwarenessPreferences, @@ -74,9 +75,28 @@ export function androidAlertForState( }; } +function alertCoversFinishedAggregate( + alertedRows: ReadonlyArray, + displayedAggregate: RelayAgentActivityAggregateState | null | undefined, +): boolean { + if (!displayedAggregate || displayedAggregate.activeCount > 0) return false; + if (displayedAggregate.activities.length === 0) return false; + const alertedKeys = new Set( + alertedRows.map((row) => + JSON.stringify([row.environmentId, row.threadId, row.phase, row.updatedAt]), + ), + ); + return displayedAggregate.activities.every( + (row) => + (row.phase === "completed" || row.phase === "failed") && + alertedKeys.has(JSON.stringify([row.environmentId, row.threadId, row.phase, row.updatedAt])), + ); +} + export function androidAlertForAggregate(input: { readonly previousAggregate: RelayAgentActivityAggregateState; readonly nextAggregate: RelayAgentActivityAggregateState; + readonly displayedAggregate?: RelayAgentActivityAggregateState | null; readonly preferences: RelayAgentAwarenessPreferences; readonly nowMs: number; }) { @@ -99,6 +119,8 @@ export function androidAlertForAggregate(input: { alert_path: notification.deepLink, }; } + const displayedAggregate = + input.displayedAggregate === undefined ? input.nextAggregate : input.displayedAggregate; return { // Stable group IDs let the native handler deduplicate across jobs, retries, and row orders. alert_id: JSON.stringify( @@ -110,6 +132,9 @@ export function androidAlertForAggregate(input: { alert_body: alert.body, // Target the overview so one visible thread cannot suppress other threads' alerts. alert_path: "/", + ...(alertCoversFinishedAggregate(activities, displayedAggregate) + ? { alert_covers_activity: "true" } + : {}), }; } @@ -269,6 +294,7 @@ const make = Effect.gen(function* () { allowedEnvironments.has(row.environmentId), ), }, + displayedAggregate: aggregate, preferences: preferences.value, nowMs: now.epochMilliseconds, });