GeezerVison is showing github.com — fix(mobile): keep Android live activity independent of alerts (#24933) · adampeterhiggins/t3code@06f8b99
File treeExpand file treeCollapse file tree Open diff view settings modules/t3-agent-notifications/android/src main/java/expo/modules/t3agentnotifications test/java/expo/modules/t3agentnotifications
src/features/agent-awareness
infra/relay/src/agentActivity
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentActivityPresentation.kt +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -115,7 +115,7 @@ internal class ActivityPresentation(data: Map<String, String>, private val activ | 115 | 115 | } | 116 | 116 |
| 117 | 117 | val chip = when { | 118 | | - !active -> null | | 118 | + !active -> if (phase == ActivityPhase.FAILED) "Failed" else "Done" | 119 | 119 | phase == null -> data["activity_chip"]?.takeIf { it.isNotBlank() }?.take(7) ?: "Active" | 120 | 120 | phase == ActivityPhase.RUNNING && activeCount > 1 -> | 121 | 121 | "${if (activeCount > 9) "9+" else activeCount} live" | |
Collapse file Copy file name to clipboardExpand all lines: apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt +7-7Lines changed: 7 additions & 7 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -297,21 +297,21 @@ object AgentNotifications { | 297 | 297 | ) | 298 | 298 | val presentation = ActivityPresentation(data, active) | 299 | 299 | val openThread = contentIntent(context, scheme, data["activity_path"], ACTIVITY_ID) | | 300 | + // Retained results still need Android's ongoing flag to remain promoted. | | 301 | + val ongoing = active || Build.VERSION.SDK_INT >= 36 | 300 | 302 | val builder = base(context, ACTIVITY_CHANNEL) | 301 | | - .setOngoing(active).setOnlyAlertOnce(true).setSilent(true) | | 303 | + .setOngoing(ongoing).setOnlyAlertOnce(true).setSilent(true) | 302 | 304 | .setTimeoutAfter(remainingMs) | 303 | 305 | // Live Updates must remain uncolorized to qualify for promotion. | 304 | 306 | .setColorized(false) | 305 | | - .setRequestPromotedOngoing(active) | 306 | | - .setShortCriticalText(presentation.chip) | | 307 | + .setRequestPromotedOngoing(ongoing) | | 308 | + .setShortCriticalText(if (ongoing) presentation.chip else null) | 307 | 309 | .setContentIntent(openThread) | 308 | 310 | .setDeleteIntent(dismissIntent) | 309 | 311 | presentation.applyTo(builder, context) | 310 | 312 | val action = presentation.action | 311 | | - if (action != null) { | 312 | | - if (openThread != null) builder.addAction(0, action, openThread) | 313 | | - builder.addAction(0, "Dismiss", dismissIntent) | 314 | | - } | | 313 | + if (action != null && openThread != null) builder.addAction(0, action, openThread) | | 314 | + if (ongoing) builder.addAction(0, "Dismiss", dismissIntent) | 315 | 315 | manager(context).notify(ACTIVITY_TAG, ACTIVITY_ID, builder.build()) | 316 | 316 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { | 317 | 317 | // Notification timeouts were added in API 26. One inexact alarm also | |
Collapse file Copy file name to clipboardExpand all lines: apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt +112-9Lines changed: 112 additions & 9 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -3,6 +3,7 @@ package expo.modules.t3agentnotifications | 3 | 3 | import android.app.Activity | 4 | 4 | import android.app.AlarmManager | 5 | 5 | import android.app.Application | | 6 | +import android.app.NotificationChannel | 6 | 7 | import android.app.Notification | 7 | 8 | import android.app.NotificationManager | 8 | 9 | import android.content.ComponentName | @@ -264,7 +265,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() { | 264 | 265 | } | 265 | 266 |
| 266 | 267 | @Test | 267 | | - fun finishedCardIsRetainedSilentlyWithoutOngoingFlagAndExpiresAtTheOriginalDeadline() { | | 268 | + fun finishedCardIsRetainedSilentlyAndExpiresAtTheOriginalDeadline() { | 268 | 269 | lifecycle.currentState = Lifecycle.State.RESUMED | 269 | 270 | val expiresAt = System.currentTimeMillis() + 15 * 60 * 1000L | 270 | 271 | val finished = update("finished", false) + mapOf( | @@ -275,7 +276,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() { | 275 | 276 | AgentNotifications.receive(context, finished) | 276 | 277 | val card = manager.activeNotifications.single().notification | 277 | 278 | assertEquals("Agent work failed", card.extras.getString(Notification.EXTRA_TITLE)) | 278 | | - assertFalse(card.flags and Notification.FLAG_ONGOING_EVENT != 0) | | 279 | + assertEquals(Build.VERSION.SDK_INT >= 36, card.flags and Notification.FLAG_ONGOING_EVENT != 0) | 279 | 280 | assertTimeout(card, 1..15 * 60 * 1000L) | 280 | 281 | AgentNotifications.receive( | 281 | 282 | context, | @@ -413,10 +414,22 @@ class AgentNotificationsTest : AgentNotificationsFixture() { | 413 | 414 | "android.app.Notification\$BigTextStyle", | 414 | 415 | card.extras.getString(Notification.EXTRA_TEMPLATE) | 415 | 416 | ) | 416 | | - assertEquals(active, NotificationCompat.isRequestPromotedOngoing(card)) | | 417 | + assertEquals( | | 418 | + active || Build.VERSION.SDK_INT >= 36, | | 419 | + NotificationCompat.isRequestPromotedOngoing(card) | | 420 | + ) | 417 | 421 | if (!active) { | 418 | | - assertEquals(null, card.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT)) | 419 | | - assertEquals(0, card.actions?.size ?: 0) | | 422 | + assertEquals( | | 423 | + if (Build.VERSION.SDK_INT < 36) { | | 424 | + null | | 425 | + } else if (phase == "failed") { | | 426 | + "Failed" | | 427 | + } else { | | 428 | + "Done" | | 429 | + }, | | 430 | + card.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT) | | 431 | + ) | | 432 | + assertEquals(if (Build.VERSION.SDK_INT >= 36) 1 else 0, card.actions?.size ?: 0) | 420 | 433 | } | 421 | 434 | } | 422 | 435 | } | @@ -566,7 +579,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() { | 566 | 579 | } | 567 | 580 |
| 568 | 581 | @Test | 569 | | - fun liveUpdateChipChangesWithActivityAndClearsOnCompletion() { | | 582 | + fun liveUpdateChipChangesWithActivityAndShowsDoneOnCompletion() { | 570 | 583 | lifecycle.currentState = Lifecycle.State.RESUMED | 571 | 584 | AgentNotifications.receive(context, update("work", true)) | 572 | 585 | assertEquals( | @@ -590,9 +603,13 @@ class AgentNotificationsTest : AgentNotificationsFixture() { | 590 | 603 | ) | 591 | 604 | ) | 592 | 605 | val finishedCard = manager.activeNotifications.single().notification | 593 | | - assertEquals(null, finishedCard.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT)) | 594 | | - assertFalse(NotificationCompat.isRequestPromotedOngoing(finishedCard)) | 595 | | - assertFalse(finishedCard.flags and Notification.FLAG_ONGOING_EVENT != 0) | | 606 | + val promoted = Build.VERSION.SDK_INT >= 36 | | 607 | + assertEquals( | | 608 | + if (promoted) "Done" else null, | | 609 | + finishedCard.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT) | | 610 | + ) | | 611 | + assertEquals(promoted, NotificationCompat.isRequestPromotedOngoing(finishedCard)) | | 612 | + assertEquals(promoted, finishedCard.flags and Notification.FLAG_ONGOING_EVENT != 0) | 596 | 613 | } | 597 | 614 |
| 598 | 615 | @Test | @@ -635,6 +652,92 @@ class AgentNotificationsTest : AgentNotificationsFixture() { | 635 | 652 | } | 636 | 653 | } | 637 | 654 |
| | 655 | +@RunWith(RobolectricTestRunner::class) | | 656 | +@Config(sdk = [26, 33, 36], manifest = Config.NONE) | | 657 | +class AgentNotificationChannelsTest { | | 658 | + @Test | | 659 | + fun mutedAlertChannelKeepsTheSameActivityThroughCompletionUntilDismissedOrExpired() { | | 660 | + val context = RuntimeEnvironment.getApplication() | | 661 | + val manager = context.getSystemService(NotificationManager::class.java) | | 662 | + shadowOf(manager).setNotificationsEnabled(true) | | 663 | + AgentNotifications.clear(context) | | 664 | + AgentNotifications.configure(context, "device", "user", "t3code-dev", true) | | 665 | + val running = mapOf( | | 666 | + "device_id" to "device", | | 667 | + "user_id" to "user", | | 668 | + "updated_at" to System.currentTimeMillis().toString(), | | 669 | + "active" to "true", | | 670 | + "activity_title" to "Agent activity" | | 671 | + ) | | 672 | + manager.createNotificationChannel( | | 673 | + NotificationChannel("agent-alerts", "Agent alerts", NotificationManager.IMPORTANCE_NONE) | | 674 | + ) | | 675 | + AgentNotifications.receive(context, running) | | 676 | + val initialCard = manager.activeNotifications.single() | | 677 | + assertEquals("t3-agent-activity", initialCard.tag) | | 678 | + | | 679 | + AgentNotifications.configure(context, "device", "user", "t3code-dev", true) | | 680 | + AgentNotifications.receive( | | 681 | + context, | | 682 | + running + mapOf( | | 683 | + "activity_phase" to "waiting_for_approval", | | 684 | + "activity_attention_count" to "1" | | 685 | + ) | | 686 | + ) | | 687 | + val card = manager.activeNotifications.single().notification | | 688 | + assertEquals("Approve", card.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT)) | | 689 | + | | 690 | + val finished = running + mapOf( | | 691 | + "active" to "false", | | 692 | + "activity_phase" to "completed", | | 693 | + "activity_line_0" to "Done\tTest thread\tTest project", | | 694 | + "activity_expires_at" to (System.currentTimeMillis() + 900000).toString() | | 695 | + ) | | 696 | + AgentNotifications.receive(context, finished) | | 697 | + AgentNotifications.receive(context, finished) | | 698 | + val completedCard = manager.activeNotifications.single() | | 699 | + assertEquals(initialCard.id, completedCard.id) | | 700 | + assertEquals(initialCard.tag, completedCard.tag) | | 701 | + assertEquals("agent-activity", completedCard.notification.channelId) | | 702 | + assertEquals( | | 703 | + "Test thread", | | 704 | + completedCard.notification.extras.getString(Notification.EXTRA_TITLE) | | 705 | + ) | | 706 | + assertEquals( | | 707 | + "Done Test project", | | 708 | + completedCard.notification.extras.getCharSequence(Notification.EXTRA_TEXT).toString() | | 709 | + ) | | 710 | + val promoted = Build.VERSION.SDK_INT >= 36 | | 711 | + assertEquals(promoted, NotificationCompat.isRequestPromotedOngoing(completedCard.notification)) | | 712 | + assertEquals( | | 713 | + promoted, | | 714 | + completedCard.notification.flags and Notification.FLAG_ONGOING_EVENT != 0 | | 715 | + ) | | 716 | + assertEquals( | | 717 | + if (promoted) "Done" else null, | | 718 | + completedCard.notification.extras.getString(NotificationCompat.EXTRA_SHORT_CRITICAL_TEXT) | | 719 | + ) | | 720 | + | | 721 | + if (promoted) { | | 722 | + val dismiss = completedCard.notification.actions.single() | | 723 | + assertEquals("Dismiss", dismiss.title.toString()) | | 724 | + AgentActivityDismissReceiver().onReceive(context, shadowOf(dismiss.actionIntent).savedIntent) | | 725 | + } else { | | 726 | + AgentNotifications.dismiss(context) | | 727 | + } | | 728 | + AgentNotifications.receive(context, finished) | | 729 | + assertTrue(manager.activeNotifications.isEmpty()) | | 730 | + | | 731 | + AgentNotifications.receive(context, running) | | 732 | + assertEquals("t3-agent-activity", manager.activeNotifications.single().tag) | | 733 | + AgentNotifications.receive( | | 734 | + context, | | 735 | + finished + ("activity_expires_at" to (System.currentTimeMillis() - 1).toString()) | | 736 | + ) | | 737 | + assertTrue(manager.activeNotifications.isEmpty()) | | 738 | + } | | 739 | +} | | 740 | + | 638 | 741 | @RunWith(RobolectricTestRunner::class) | 639 | 742 | @Config(sdk = [24, 26, 33, 36], manifest = Config.NONE) | 640 | 743 | class AgentNotificationsCompletionTest : AgentNotificationsFixture() { | |
Collapse file Copy file name to clipboardExpand all lines: apps/mobile/src/features/agent-awareness/registrationPayload.ts +10-2Lines changed: 10 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -21,11 +21,19 @@ export function makeRelayDeviceRegistrationRequest( | 21 | 21 | readonly preferences: Preferences; | 22 | 22 | } & ( | 23 | 23 | | { readonly platform?: "ios"; readonly iosMajorVersion: number } | 24 | | - | { readonly platform: "android"; readonly androidApiLevel: number } | | 24 | + | { | | 25 | + readonly platform: "android"; | | 26 | + readonly androidApiLevel: number; | | 27 | + readonly notificationPermissionGranted: boolean; | | 28 | + } | 25 | 29 | ), | 26 | 30 | ): RelayDeviceRegistrationRequest { | 27 | 31 | const pushAvailable = supportsAgentAwarenessPush(); | 28 | | - const liveActivitiesEnabled = pushAvailable && input.preferences.liveActivitiesEnabled !== false; | | 32 | + const liveActivitiesEnabled = | | 33 | + pushAvailable && | | 34 | + input.preferences.liveActivitiesEnabled !== false && | | 35 | + (input.platform !== "android" || | | 36 | + (input.notificationPermissionGranted && Boolean(input.pushToken))); | 29 | 37 | return { | 30 | 38 | deviceId: input.deviceId, | 31 | 39 | label: input.label, | |
Collapse file Copy file name to clipboardExpand all lines: apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts +89-3Lines changed: 89 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -114,6 +114,8 @@ vi.mock("../../state/server", () => ({ | 114 | 114 | })); | 115 | 115 |
| 116 | 116 | vi.mock("expo-notifications", () => ({ | | 117 | + AndroidImportance: { NONE: 0, HIGH: 4 }, | | 118 | + getNotificationChannelAsync: vi.fn(() => Promise.resolve(null)), | 117 | 119 | addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })), | 118 | 120 | getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })), | 119 | 121 | getPermissionsAsync: vi.fn(() => Promise.resolve({ granted: true })), | @@ -248,6 +250,11 @@ describe("makeRelayDeviceRegistrationRequest", () => { | 248 | 250 | type: "ios", | 249 | 251 | data: "apns-token", | 250 | 252 | }); | | 253 | + vi.mocked(Notifications.getPermissionsAsync).mockReset(); | | 254 | + vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ | | 255 | + granted: true, | | 256 | + } as Awaited<ReturnType<typeof Notifications.getPermissionsAsync>>); | | 257 | + vi.mocked(Notifications.getNotificationChannelAsync).mockResolvedValue(null); | 251 | 258 | vi.unstubAllGlobals(); | 252 | 259 | vi.stubGlobal("__DEV__", false); | 253 | 260 | secureStore.clear(); | @@ -260,6 +267,7 @@ describe("makeRelayDeviceRegistrationRequest", () => { | 260 | 267 | vi.mocked(loadAgentAwarenessRegistrationRecord).mockClear(); | 261 | 268 | vi.mocked(clearAgentAwarenessRegistrationRecord).mockClear(); | 262 | 269 | vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1"); | | 270 | + vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: false }); | 263 | 271 | widgetMocks.getInstances.mockReset(); | 264 | 272 | widgetMocks.getInstances.mockReturnValue([]); | 265 | 273 | widgetMocks.start.mockClear(); | @@ -634,6 +642,7 @@ describe("makeRelayDeviceRegistrationRequest", () => { | 634 | 642 | it.effect.each(["ios", "android"] as const)( | 635 | 643 | "does not enable %s notifications when a token rotates after permission is revoked", | 636 | 644 | (os) => { | | 645 | + vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: true }); | 637 | 646 | vi.spyOn(Platform, "OS", "get").mockReturnValue(os); | 638 | 647 | vi.spyOn(Platform, "Version", "get").mockReturnValue(os === "ios" ? 18 : 36); | 639 | 648 | vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({ | @@ -660,7 +669,7 @@ describe("makeRelayDeviceRegistrationRequest", () => { | 660 | 669 | return Effect.gen(function* () { | 661 | 670 | yield* runBackgroundOperations(); | 662 | 671 | expect(registrations.at(-1)).toMatchObject({ | 663 | | - preferences: { notificationsEnabled: true }, | | 672 | + preferences: { notificationsEnabled: true, liveActivitiesEnabled: true }, | 664 | 673 | }); | 665 | 674 | vi.mocked(Notifications.getPermissionsAsync).mockResolvedValueOnce({ | 666 | 675 | granted: false, | @@ -669,9 +678,21 @@ describe("makeRelayDeviceRegistrationRequest", () => { | 669 | 678 | listener({ type: os, data: "rotated" }); | 670 | 679 | yield* runBackgroundOperations(); | 671 | 680 | expect(registrations.at(-1)).toMatchObject({ | 672 | | - preferences: { notificationsEnabled: false }, | | 681 | + preferences: { notificationsEnabled: false, liveActivitiesEnabled: os === "ios" }, | 673 | 682 | }); | 674 | | - expect(registrations.at(-1)).not.toHaveProperty("pushToken"); | | 683 | + if (os === "android") { | | 684 | + expect(registrations.at(-1)).toMatchObject({ pushToken: "rotated" }); | | 685 | + vi.mocked(Notifications.getPermissionsAsync).mockResolvedValueOnce({ | | 686 | + granted: false, | | 687 | + } as Awaited<ReturnType<typeof Notifications.getPermissionsAsync>>); | | 688 | + yield* refreshAgentAwarenessRegistration(); | | 689 | + expect(registrations.at(-1)).toMatchObject({ | | 690 | + pushToken: "initial", | | 691 | + preferences: { notificationsEnabled: false, liveActivitiesEnabled: false }, | | 692 | + }); | | 693 | + } else { | | 694 | + expect(registrations.at(-1)).not.toHaveProperty("pushToken"); | | 695 | + } | 675 | 696 | }).pipe( | 676 | 697 | Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch), | 677 | 698 | Effect.provide( | @@ -682,6 +703,71 @@ describe("makeRelayDeviceRegistrationRequest", () => { | 682 | 703 | ); | 683 | 704 | }, | 684 | 705 | ); | | 706 | + it.effect.each(["blocked", "unavailable"] as const)( | | 707 | + "keeps Android push delivery registered when the alert channel is %s", | | 708 | + (channelState) => { | | 709 | + vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: true }); | | 710 | + vi.spyOn(Platform, "OS", "get").mockReturnValue("android"); | | 711 | + vi.spyOn(Platform, "Version", "get").mockReturnValue(36); | | 712 | + vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({ | | 713 | + type: "android", | | 714 | + data: "fcm-token", | | 715 | + }); | | 716 | + vi.mocked(Notifications.getNotificationChannelAsync).mockResolvedValue({ | | 717 | + id: "agent-alerts", | | 718 | + name: "Agent alerts", | | 719 | + importance: Notifications.AndroidImportance.NONE, | | 720 | + } as Awaited<ReturnType<typeof Notifications.getNotificationChannelAsync>>); | | 721 | + if (channelState === "unavailable") { | | 722 | + vi.mocked(Notifications.getNotificationChannelAsync).mockRejectedValue( | | 723 | + new Error("Android channel lookup failed"), | | 724 | + ); | | 725 | + } | | 726 | + const registrations: unknown[] = []; | | 727 | + vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => { | | 728 | + const request = new Request(input, init); | | 729 | + if (request.url.endsWith("/v1/client/dpop-token")) { | | 730 | + return Response.json({ | | 731 | + access_token: "dpop", | | 732 | + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", | | 733 | + token_type: "DPoP", | | 734 | + expires_in: 300, | | 735 | + scope: "mobile:registration", | | 736 | + }); | | 737 | + } | | 738 | + registrations.push(await request.json()); | | 739 | + return Response.json({ ok: true }); | | 740 | + }); | | 741 | + Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } }; | | 742 | + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk"), "user-a"); | | 743 | + return Effect.gen(function* () { | | 744 | + yield* runBackgroundOperations(); | | 745 | + expect(registrations.at(-1)).toMatchObject({ | | 746 | + pushToken: "fcm-token", | | 747 | + preferences: { notificationsEnabled: false, liveActivitiesEnabled: true }, | | 748 | + }); | | 749 | + expect(getAgentAwarenessRegistrationStatus()).toBe("registered"); | | 750 | + | | 751 | + const listener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)![0]; | | 752 | + listener({ type: "android", data: "rotated-fcm-token" }); | | 753 | + yield* runBackgroundOperations(); | | 754 | + expect(registrations.at(-1)).toMatchObject({ | | 755 | + pushToken: "rotated-fcm-token", | | 756 | + preferences: { notificationsEnabled: false, liveActivitiesEnabled: true }, | | 757 | + }); | | 758 | + | | 759 | + vi.mocked(Notifications.getNotificationChannelAsync).mockResolvedValue(null); | | 760 | + yield* refreshAgentAwarenessRegistration(); | | 761 | + expect(registrations.at(-1)).toMatchObject({ | | 762 | + pushToken: "fcm-token", | | 763 | + preferences: { notificationsEnabled: true }, | | 764 | + }); | | 765 | + }).pipe( | | 766 | + Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch), | | 767 | + Effect.provide(layerRelayTest), | | 768 | + ); | | 769 | + }, | | 770 | + ); | 685 | 771 | it.effect("preserves relay rejection errors with React Native response headers", () => { | 686 | 772 | vi.spyOn(Platform, "OS", "get").mockReturnValue("android"); | 687 | 773 | vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({ | |
|