Skip to content

Commit 03a1ba0

Browse files
committed
fix(mobile): keep Android live activity independent of alerts
1 parent 5b35402 commit 03a1ba0

9 files changed

Lines changed: 168 additions & 17 deletions

File tree

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import Constants from "expo-constants";
2+
import * as Application from "expo-application";
23
import { requireOptionalNativeModule } from "expo";
34
import { Linking, Platform } from "react-native";
45

@@ -50,6 +51,17 @@ export function supportsAndroidLiveUpdateSettings(): boolean {
5051
return Platform.OS === "android" && Number(Platform.Version) >= 36;
5152
}
5253

54+
export async function openAndroidAgentAlertSettings(): Promise<void> {
55+
if (Number(Platform.Version) < 26 || !Application.applicationId) {
56+
await Linking.openSettings();
57+
return;
58+
}
59+
await Linking.sendIntent("android.settings.CHANNEL_NOTIFICATION_SETTINGS", [
60+
{ key: "android.provider.extra.APP_PACKAGE", value: Application.applicationId },
61+
{ key: "android.provider.extra.CHANNEL_ID", value: "agent-alerts" },
62+
]);
63+
}
64+
5365
export async function openAndroidLiveUpdateSettings(): Promise<void> {
5466
if (!native?.openLiveUpdateSettings?.()) {
5567
await Linking.openSettings();

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,12 @@ import * as Effect from "effect/Effect";
33
import * as Schema from "effect/Schema";
44
import { Platform } from "react-native";
55

6+
export async function isAgentAlertChannelEnabled(): Promise<boolean> {
7+
if (Platform.OS !== "android" || Number(Platform.Version) < 26) return true;
8+
const channel = await Notifications.getNotificationChannelAsync("agent-alerts");
9+
return channel?.importance !== Notifications.AndroidImportance.NONE;
10+
}
11+
612
export type NotificationPermissionResult =
713
| { readonly type: "unsupported" }
814
| { readonly type: "granted" }

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@ export function makeRelayDeviceRegistrationRequest(
2525
),
2626
): RelayDeviceRegistrationRequest {
2727
const pushAvailable = supportsAgentAwarenessPush();
28-
const liveActivitiesEnabled = pushAvailable && input.preferences.liveActivitiesEnabled !== false;
28+
const liveActivitiesEnabled =
29+
pushAvailable &&
30+
input.preferences.liveActivitiesEnabled !== false &&
31+
(input.platform !== "android" || Boolean(input.pushToken));
2932
return {
3033
deviceId: input.deviceId,
3134
label: input.label,

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

Lines changed: 69 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
clearAgentAwarenessRegistrationRecord,
2323
loadAgentAwarenessRegistrationRecord,
2424
loadOrCreateAgentAwarenessDeviceId,
25+
loadPreferences,
2526
saveAgentAwarenessRegistrationRecord,
2627
} from "../../persistence/imperative";
2728
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
@@ -106,6 +107,8 @@ vi.mock("../../state/server", () => ({
106107
}));
107108

108109
vi.mock("expo-notifications", () => ({
110+
AndroidImportance: { NONE: 0, HIGH: 4 },
111+
getNotificationChannelAsync: vi.fn(() => Promise.resolve(null)),
109112
addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),
110113
getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })),
111114
getPermissionsAsync: vi.fn(() => Promise.resolve({ granted: true })),
@@ -247,6 +250,11 @@ describe("makeRelayDeviceRegistrationRequest", () => {
247250
type: "ios",
248251
data: "apns-token",
249252
});
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);
250258
vi.unstubAllGlobals();
251259
vi.stubGlobal("__DEV__", false);
252260
secureStore.clear();
@@ -259,6 +267,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
259267
vi.mocked(loadAgentAwarenessRegistrationRecord).mockClear();
260268
vi.mocked(clearAgentAwarenessRegistrationRecord).mockClear();
261269
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
270+
vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: false });
262271
widgetMocks.getInstances.mockReset();
263272
widgetMocks.getInstances.mockReturnValue([]);
264273
widgetMocks.start.mockClear();
@@ -662,6 +671,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
662671
it.effect.each(["ios", "android"] as const)(
663672
"does not enable %s notifications when a token rotates after permission is revoked",
664673
(os) => {
674+
vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: true });
665675
vi.spyOn(Platform, "OS", "get").mockReturnValue(os);
666676
vi.spyOn(Platform, "Version", "get").mockReturnValue(os === "ios" ? 18 : 36);
667677
vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
@@ -688,7 +698,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
688698
return Effect.gen(function* () {
689699
yield* runBackgroundOperations();
690700
expect(registrations.at(-1)).toMatchObject({
691-
preferences: { notificationsEnabled: true },
701+
preferences: { notificationsEnabled: true, liveActivitiesEnabled: true },
692702
});
693703
vi.mocked(Notifications.getPermissionsAsync).mockResolvedValueOnce({
694704
granted: false,
@@ -697,7 +707,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
697707
listener({ type: os, data: "rotated" });
698708
yield* runBackgroundOperations();
699709
expect(registrations.at(-1)).toMatchObject({
700-
preferences: { notificationsEnabled: false },
710+
preferences: { notificationsEnabled: false, liveActivitiesEnabled: os === "ios" },
701711
});
702712
expect(registrations.at(-1)).not.toHaveProperty("pushToken");
703713
}).pipe(
@@ -710,6 +720,63 @@ describe("makeRelayDeviceRegistrationRequest", () => {
710720
);
711721
},
712722
);
723+
it.effect("keeps Android push delivery registered when only the alert channel is blocked", () => {
724+
vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: true });
725+
vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
726+
vi.spyOn(Platform, "Version", "get").mockReturnValue(36);
727+
vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
728+
type: "android",
729+
data: "fcm-token",
730+
});
731+
vi.mocked(Notifications.getNotificationChannelAsync).mockResolvedValue({
732+
id: "agent-alerts",
733+
name: "Agent alerts",
734+
importance: Notifications.AndroidImportance.NONE,
735+
} as Awaited<ReturnType<typeof Notifications.getNotificationChannelAsync>>);
736+
const registrations: unknown[] = [];
737+
vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
738+
const request = new Request(input, init);
739+
if (request.url.endsWith("/v1/client/dpop-token")) {
740+
return Response.json({
741+
access_token: "dpop",
742+
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
743+
token_type: "DPoP",
744+
expires_in: 300,
745+
scope: "mobile:registration",
746+
});
747+
}
748+
registrations.push(await request.json());
749+
return Response.json({ ok: true });
750+
});
751+
Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } };
752+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk"), "user-a");
753+
return Effect.gen(function* () {
754+
yield* runBackgroundOperations();
755+
expect(registrations.at(-1)).toMatchObject({
756+
pushToken: "fcm-token",
757+
preferences: { notificationsEnabled: false, liveActivitiesEnabled: true },
758+
});
759+
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
760+
761+
const listener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)![0];
762+
listener({ type: "android", data: "rotated-fcm-token" });
763+
yield* runBackgroundOperations();
764+
expect(registrations.at(-1)).toMatchObject({
765+
pushToken: "rotated-fcm-token",
766+
preferences: { notificationsEnabled: false, liveActivitiesEnabled: true },
767+
});
768+
769+
vi.mocked(Notifications.getNotificationChannelAsync).mockResolvedValue(null);
770+
yield* refreshAgentAwarenessRegistration();
771+
expect(registrations.at(-1)).toMatchObject({
772+
pushToken: "fcm-token",
773+
preferences: { notificationsEnabled: true },
774+
});
775+
}).pipe(
776+
Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
777+
Effect.provide(layerRelayTest),
778+
);
779+
});
713780
it.effect("preserves relay rejection errors with React Native response headers", () => {
714781
vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
715782
vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import {
4444
} from "./agentLiveActivity";
4545
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
4646
import { supportsAgentAwarenessPush } from "./capabilities";
47+
import { isAgentAlertChannelEnabled } from "./notificationPermissions";
4748
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
4849

4950
const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
@@ -262,8 +263,19 @@ const nativePushTokenRegistration = Effect.fn("remoteRegistration.nativePushToke
262263
if (!permissions.granted) {
263264
return { notificationsEnabled: false, pushToken: null };
264265
}
266+
const alertsEnabled =
267+
Platform.OS === "android"
268+
? yield* Effect.tryPromise({
269+
try: isAgentAlertChannelEnabled,
270+
catch: (cause) =>
271+
new AgentAwarenessOperationError({
272+
operation: "read-notification-permissions",
273+
cause,
274+
}),
275+
})
276+
: true;
265277
if (observedPushToken) {
266-
return { notificationsEnabled: true, pushToken: observedPushToken };
278+
return { notificationsEnabled: alertsEnabled, pushToken: observedPushToken };
267279
}
268280
const token = yield* Effect.tryPromise({
269281
try: () => Notifications.getDevicePushTokenAsync(),
@@ -284,7 +296,7 @@ const nativePushTokenRegistration = Effect.fn("remoteRegistration.nativePushToke
284296
token?.type === Platform.OS && typeof token.data === "string" && token.data.trim().length > 0
285297
? token.data.trim()
286298
: null;
287-
return { notificationsEnabled: pushToken !== null, pushToken };
299+
return { notificationsEnabled: alertsEnabled && pushToken !== null, pushToken };
288300
},
289301
);
290302

‎apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx‎

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,15 @@ import {
2222
} from "@t3tools/client-runtime/state/runtime";
2323
import { supportsAgentAwarenessPush } from "../agent-awareness/capabilities";
2424
import {
25+
openAndroidAgentAlertSettings,
2526
openAndroidLiveUpdateSettings,
2627
supportsAndroidLiveUpdateSettings,
2728
} from "../agent-awareness/androidNotifications";
2829
import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences";
29-
import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";
30+
import {
31+
isAgentAlertChannelEnabled,
32+
requestAgentNotificationPermission,
33+
} from "../agent-awareness/notificationPermissions";
3034
import {
3135
getAgentAwarenessRegistrationStatus,
3236
refreshAgentAwarenessRegistration,
@@ -106,13 +110,16 @@ function ConfiguredSettingsNotificationsRouteScreen() {
106110
setNotificationStatus("unsupported");
107111
return;
108112
}
109-
const result = await settlePromise(() => Notifications.getPermissionsAsync());
113+
const result = await settlePromise(async () => {
114+
const permission = await Notifications.getPermissionsAsync();
115+
return permission.granted && (await isAgentAlertChannelEnabled());
116+
});
110117
if (result._tag === "Failure") {
111118
reportAtomCommandResult(result, { label: "notification permission refresh" });
112119
setNotificationStatus("disabled");
113120
return;
114121
}
115-
setNotificationStatus(result.value.granted ? "enabled" : "disabled");
122+
setNotificationStatus(result.value ? "enabled" : "disabled");
116123
};
117124

118125
useEffect(() => {
@@ -146,6 +153,16 @@ function ConfiguredSettingsNotificationsRouteScreen() {
146153
);
147154
}, [isLoaded, isSignedIn, preferencesResult]);
148155

156+
const openAlertSettings = async () => {
157+
const result = await settlePromise(openAndroidAgentAlertSettings);
158+
if (result._tag === "Failure") {
159+
Dialog.alert(
160+
"Couldn't open Settings",
161+
"Open Android Settings, select T3 Code, then select Agent alerts in Notifications.",
162+
);
163+
}
164+
};
165+
149166
const requestNotifications = async () => {
150167
const result = await settleAsyncResult(() =>
151168
runtime.runPromiseExit(
@@ -167,6 +184,16 @@ function ConfiguredSettingsNotificationsRouteScreen() {
167184
return;
168185
}
169186
if (result.value.type === "granted") {
187+
const channel = await settlePromise(isAgentAlertChannelEnabled);
188+
if (channel._tag === "Failure") {
189+
reportAtomCommandResult(channel, { label: "notification channel refresh" });
190+
return;
191+
}
192+
if (!channel.value) {
193+
setNotificationStatus("disabled");
194+
void openAlertSettings();
195+
return;
196+
}
170197
setNotificationStatus("enabled");
171198
if (getAgentAwarenessRegistrationStatus() === "registered") {
172199
Dialog.alert("Notifications enabled", "Agent notifications are enabled for this device.");
@@ -247,7 +274,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
247274
);
248275
return;
249276
}
250-
setNotificationStatus("enabled");
277+
await refreshNotifications();
251278
}
252279
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
253280
if (tokenResult._tag === "Failure") {
@@ -320,6 +347,11 @@ function ConfiguredSettingsNotificationsRouteScreen() {
320347
return;
321348
}
322349

350+
if (Platform.OS === "android") {
351+
void openAlertSettings();
352+
return;
353+
}
354+
323355
Dialog.alert(
324356
"Disable notifications",
325357
"Open system Settings to disable notifications for T3 Code.",
@@ -403,14 +435,20 @@ function ConfiguredSettingsNotificationsRouteScreen() {
403435
<SettingsSection title="Agent activity">
404436
<SettingsSwitchRow
405437
icon="bell.badge"
406-
label="Device Notifications"
438+
label={Platform.OS === "android" ? "Agent Alerts" : "Device Notifications"}
407439
disabled={
408440
!agentAwarenessPlatform.supported ||
409441
!agentAwarenessPushAvailable ||
410442
notificationStatus === "checking" ||
411443
notificationStatus === "unsupported"
412444
}
413-
subtitle={agentAwarenessSubtitle}
445+
subtitle={
446+
Platform.OS === "android" &&
447+
Number(Platform.Version) >= 26 &&
448+
agentAwarenessPushAvailable
449+
? "Separate from ongoing agent activity"
450+
: agentAwarenessSubtitle
451+
}
414452
value={
415453
agentAwarenessPushAvailable && notificationStatus === "enabled" && deviceRegistered
416454
}

‎docs/user/mobile-notifications.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
# Mobile notifications
22

3-
Sign in to T3 Connect, link your environments, and enable **Device Notifications** in **Settings → Notifications** to receive alerts when an agent finishes, fails, needs approval, or asks for input. Tap a notification to open its thread. Your environment must have agent activity publishing enabled.
3+
Sign in to T3 Connect, link your environments, and enable **Agent Alerts** on Android or **Device Notifications** on iOS in **Settings → Notifications** to receive alerts when an agent finishes, fails, needs approval, or asks for input. Tap a notification to open its thread. Your environment must have agent activity publishing enabled.
44

55
Enable **Ongoing Agent Activity** on Android or **Live Activity Updates** on iOS to follow work without opening the app. Finished results remain visible for up to 15 minutes. You can dismiss an Android activity card without disabling alerts; turn off ongoing activity in Settings to stop future cards.
66

77
Ordinary alerts stay quiet while the mobile app is in the foreground. Ongoing activity continues to update. Viewing a thread on another device does not silence your phone's alerts.
88

99
Android notifications require Android 7.0 or newer and Google Play services. Android 16 and newer can promote ongoing activity to a Live Update, subject to system settings and device support. Other devices show a regular ongoing notification. Android 7's battery-saving modes can delay removal of expired cards.
1010

11+
On Android 8 and newer, **Agent Alerts** opens the system settings for the **Agent alerts** channel. Disable that channel to keep ongoing activity without regular alerts accumulating in your notification shade. Leave app notification permission and the **Ongoing agent activity** channel enabled; disabling either also hides Live Updates.
12+
1113
Notification permission and Android notification channels are controlled in system Settings. Background delivery requires T3 Connect; a direct or Tailscale connection alone does not enable push notifications. The mobile app does not need to maintain a connection to your environment. Force-stopping the Android app in system Settings prevents push delivery until you open it again.

‎infra/relay/src/agentActivity/FcmDeliveries.test.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -524,8 +524,22 @@ describe("Android delivery routing", () => {
524524
});
525525
h.current.target.last_aggregate_json = encodeJson(aggregateFor([state]));
526526
yield* delivery.process({ ...h.job, state: h.current.state });
527-
expect(h.sent[1]?.data.active).toBe("false");
527+
expect(h.sent[1]?.data.active).toBe("true");
528528
expect(h.sent[1]?.data.alert_id).toBeUndefined();
529+
expect(h.marked.at(-1)?.kind).toBe("live_activity_update");
530+
}).pipe(Effect.provide(h.layer));
531+
});
532+
533+
it.effect("starts ongoing activity without ordinary notifications or a previous card", () => {
534+
const h = harness();
535+
h.current.target.preferences_json = encodeJson({ ...preferences, notificationsEnabled: false });
536+
return Effect.gen(function* () {
537+
const delivery = yield* FcmDeliveries.FcmDeliveries;
538+
yield* delivery.process(h.job);
539+
expect(h.sent).toHaveLength(1);
540+
expect(h.sent[0]?.data.active).toBe("true");
541+
expect(h.sent[0]?.alert).toBe(false);
542+
expect(h.sent[0]?.data.alert_id).toBeUndefined();
529543
}).pipe(Effect.provide(h.layer));
530544
});
531545

‎infra/relay/src/agentActivity/FcmDeliveries.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -281,10 +281,7 @@ export const make = Effect.gen(function* () {
281281
alert = androidAlertForState(state, preferences.value, now.epochMilliseconds);
282282
}
283283
}
284-
const displayedAggregate =
285-
preferences.value.notificationsEnabled && preferences.value.liveActivitiesEnabled
286-
? aggregate
287-
: null;
284+
const displayedAggregate = preferences.value.liveActivitiesEnabled ? aggregate : null;
288285
const active = (displayedAggregate?.activeCount ?? 0) > 0;
289286
if (!displayedAggregate && !alert && !previousAggregate && job.state !== null) return;
290287
const data: Record<string, string> = {

0 commit comments

Comments
 (0)