GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(mobile): keep Android live activity independent of alerts (#24933) · adampeterhiggins/t3code@06f8b99

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/mobile
    • modules/t3-agent-notifications/android/src
      • main/java/expo/modules/t3agentnotifications
        • AgentActivityPresentation.kt
        • AgentNotifications.kt
      • test/java/expo/modules/t3agentnotifications
        • AgentNotificationsTest.kt
    • src/features/agent-awareness
      • registrationPayload.ts
      • remoteRegistration.test.ts
      • remoteRegistration.ts
  • docs/user
    • mobile-notifications.md
  • infra/relay/src/agentActivity
    • FcmDeliveries.test.ts
    • FcmDeliveries.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentActivityPresentation.kt‎

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 numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ internal class ActivityPresentation(data: Map<String, String>, private val activ
115115
}
116116

117117
val chip = when {
118-
!active -> null
118+
!active -> if (phase == ActivityPhase.FAILED) "Failed" else "Done"
119119
phase == null -> data["activity_chip"]?.takeIf { it.isNotBlank() }?.take(7) ?: "Active"
120120
phase == ActivityPhase.RUNNING && activeCount > 1 ->
121121
"${if (activeCount > 9) "9+" else activeCount} live"
Collapse file

‎apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt‎

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 numberDiff line numberDiff line change
@@ -297,21 +297,21 @@ object AgentNotifications {
297297
)
298298
val presentation = ActivityPresentation(data, active)
299299
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
300302
val builder = base(context, ACTIVITY_CHANNEL)
301-
.setOngoing(active).setOnlyAlertOnce(true).setSilent(true)
303+
.setOngoing(ongoing).setOnlyAlertOnce(true).setSilent(true)
302304
.setTimeoutAfter(remainingMs)
303305
// Live Updates must remain uncolorized to qualify for promotion.
304306
.setColorized(false)
305-
.setRequestPromotedOngoing(active)
306-
.setShortCriticalText(presentation.chip)
307+
.setRequestPromotedOngoing(ongoing)
308+
.setShortCriticalText(if (ongoing) presentation.chip else null)
307309
.setContentIntent(openThread)
308310
.setDeleteIntent(dismissIntent)
309311
presentation.applyTo(builder, context)
310312
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)
315315
manager(context).notify(ACTIVITY_TAG, ACTIVITY_ID, builder.build())
316316
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
317317
// Notification timeouts were added in API 26. One inexact alarm also
Collapse file

‎apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt‎

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 numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package expo.modules.t3agentnotifications
33
import android.app.Activity
44
import android.app.AlarmManager
55
import android.app.Application
6+
import android.app.NotificationChannel
67
import android.app.Notification
78
import android.app.NotificationManager
89
import android.content.ComponentName
@@ -264,7 +265,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() {
264265
}
265266

266267
@Test
267-
fun finishedCardIsRetainedSilentlyWithoutOngoingFlagAndExpiresAtTheOriginalDeadline() {
268+
fun finishedCardIsRetainedSilentlyAndExpiresAtTheOriginalDeadline() {
268269
lifecycle.currentState = Lifecycle.State.RESUMED
269270
val expiresAt = System.currentTimeMillis() + 15 * 60 * 1000L
270271
val finished = update("finished", false) + mapOf(
@@ -275,7 +276,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() {
275276
AgentNotifications.receive(context, finished)
276277
val card = manager.activeNotifications.single().notification
277278
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)
279280
assertTimeout(card, 1..15 * 60 * 1000L)
280281
AgentNotifications.receive(
281282
context,
@@ -413,10 +414,22 @@ class AgentNotificationsTest : AgentNotificationsFixture() {
413414
"android.app.Notification\$BigTextStyle",
414415
card.extras.getString(Notification.EXTRA_TEMPLATE)
415416
)
416-
assertEquals(active, NotificationCompat.isRequestPromotedOngoing(card))
417+
assertEquals(
418+
active || Build.VERSION.SDK_INT >= 36,
419+
NotificationCompat.isRequestPromotedOngoing(card)
420+
)
417421
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)
420433
}
421434
}
422435
}
@@ -566,7 +579,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() {
566579
}
567580

568581
@Test
569-
fun liveUpdateChipChangesWithActivityAndClearsOnCompletion() {
582+
fun liveUpdateChipChangesWithActivityAndShowsDoneOnCompletion() {
570583
lifecycle.currentState = Lifecycle.State.RESUMED
571584
AgentNotifications.receive(context, update("work", true))
572585
assertEquals(
@@ -590,9 +603,13 @@ class AgentNotificationsTest : AgentNotificationsFixture() {
590603
)
591604
)
592605
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)
596613
}
597614

598615
@Test
@@ -635,6 +652,92 @@ class AgentNotificationsTest : AgentNotificationsFixture() {
635652
}
636653
}
637654

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+
638741
@RunWith(RobolectricTestRunner::class)
639742
@Config(sdk = [24, 26, 33, 36], manifest = Config.NONE)
640743
class AgentNotificationsCompletionTest : AgentNotificationsFixture() {
Collapse file

‎apps/mobile/src/features/agent-awareness/registrationPayload.ts‎

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 numberDiff line numberDiff line change
@@ -21,11 +21,19 @@ export function makeRelayDeviceRegistrationRequest(
2121
readonly preferences: Preferences;
2222
} & (
2323
| { 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+
}
2529
),
2630
): RelayDeviceRegistrationRequest {
2731
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)));
2937
return {
3038
deviceId: input.deviceId,
3139
label: input.label,
Collapse file

‎apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts‎

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 numberDiff line numberDiff line change
@@ -114,6 +114,8 @@ vi.mock("../../state/server", () => ({
114114
}));
115115

116116
vi.mock("expo-notifications", () => ({
117+
AndroidImportance: { NONE: 0, HIGH: 4 },
118+
getNotificationChannelAsync: vi.fn(() => Promise.resolve(null)),
117119
addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),
118120
getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })),
119121
getPermissionsAsync: vi.fn(() => Promise.resolve({ granted: true })),
@@ -248,6 +250,11 @@ describe("makeRelayDeviceRegistrationRequest", () => {
248250
type: "ios",
249251
data: "apns-token",
250252
});
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);
251258
vi.unstubAllGlobals();
252259
vi.stubGlobal("__DEV__", false);
253260
secureStore.clear();
@@ -260,6 +267,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
260267
vi.mocked(loadAgentAwarenessRegistrationRecord).mockClear();
261268
vi.mocked(clearAgentAwarenessRegistrationRecord).mockClear();
262269
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
270+
vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: false });
263271
widgetMocks.getInstances.mockReset();
264272
widgetMocks.getInstances.mockReturnValue([]);
265273
widgetMocks.start.mockClear();
@@ -634,6 +642,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
634642
it.effect.each(["ios", "android"] as const)(
635643
"does not enable %s notifications when a token rotates after permission is revoked",
636644
(os) => {
645+
vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: true });
637646
vi.spyOn(Platform, "OS", "get").mockReturnValue(os);
638647
vi.spyOn(Platform, "Version", "get").mockReturnValue(os === "ios" ? 18 : 36);
639648
vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
@@ -660,7 +669,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
660669
return Effect.gen(function* () {
661670
yield* runBackgroundOperations();
662671
expect(registrations.at(-1)).toMatchObject({
663-
preferences: { notificationsEnabled: true },
672+
preferences: { notificationsEnabled: true, liveActivitiesEnabled: true },
664673
});
665674
vi.mocked(Notifications.getPermissionsAsync).mockResolvedValueOnce({
666675
granted: false,
@@ -669,9 +678,21 @@ describe("makeRelayDeviceRegistrationRequest", () => {
669678
listener({ type: os, data: "rotated" });
670679
yield* runBackgroundOperations();
671680
expect(registrations.at(-1)).toMatchObject({
672-
preferences: { notificationsEnabled: false },
681+
preferences: { notificationsEnabled: false, liveActivitiesEnabled: os === "ios" },
673682
});
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+
}
675696
}).pipe(
676697
Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
677698
Effect.provide(
@@ -682,6 +703,71 @@ describe("makeRelayDeviceRegistrationRequest", () => {
682703
);
683704
},
684705
);
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+
);
685771
it.effect("preserves relay rejection errors with React Native response headers", () => {
686772
vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
687773
vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.