Open History to see the last commit
1import { AuthRelayWriteScope } from "@t3tools/contracts";
2import { readEnvironmentScope } from "../../state/session";
3import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
4import { useAuth } from "@clerk/expo";
5import { useAtomSet, useAtomValue } from "@effect/atom-react";
6import * as Notifications from "expo-notifications";
7import { useNavigation } from "@react-navigation/native";
8import * as Effect from "effect/Effect";
9import { AsyncResult } from "effect/reactivity";
10import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
11import { Alert, AppState, Linking, Platform } from "react-native";
12import { useSafeAreaInsets } from "react-native-safe-area-context";
13
14import { AppText as Text } from "../../components/AppText";
15import {
16 isAtomCommandInterrupted,
17 reportAtomCommandResult,
18 settleAsyncResult,
19 settlePromise,
20 squashAtomCommandFailure,
21} from "@t3tools/client-runtime/state/runtime";
22import { supportsAgentAwarenessPush } from "../agent-awareness/capabilities";
23import {
24 openAndroidLiveUpdateSettings,
25 supportsAndroidLiveUpdateSettings,
26} from "../agent-awareness/androidNotifications";
27import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences";
28import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";
29import {
30 getAgentAwarenessRegistrationStatus,
31 refreshAgentAwarenessRegistration,
32 subscribeAgentAwarenessRegistrationStatus,
33} from "../agent-awareness/remoteRegistration";
34import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
35import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
36import { runtime } from "../../lib/runtime";
37import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
38import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
39import { SettingsRow } from "./components/SettingsRow";
40import { SettingsSection } from "./components/SettingsSection";
41import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
42import { SettingsScreen } from "./components/SettingsScreen";
43import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
44
45type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
46type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
47
48// Reflects whether the relay actually accepted this device's registration.
49// The notification and Live Activity switches are gated on this so they can
50// never read as enabled when the device cannot receive anything (e.g. the
51// registration request timed out).
52function useDeviceRegistered(): boolean {
53 const status = useSyncExternalStore(
54 subscribeAgentAwarenessRegistrationStatus,
55 getAgentAwarenessRegistrationStatus,
56 () => "unknown" as const,
57 );
58 return status === "registered";
59}
60
61export function SettingsNotificationsRouteScreen() {
62 if (!hasCloudPublicConfig()) {
63 return (
64 <SettingsScreen title="Notifications">
65 <ScrollView
66 contentInsetAdjustmentBehavior="automatic"
67 contentContainerClassName="px-5 pt-4"
68 >
69 <Text className="text-base text-foreground-muted">
70 Notifications require T3 Connect in this app build.
71 </Text>
72 </ScrollView>
73 </SettingsScreen>
74 );
75 }
76
77 return <ConfiguredSettingsNotificationsRouteScreen />;
78}
79
80function ConfiguredSettingsNotificationsRouteScreen() {
81 const preferencesResult = useAtomValue(mobilePreferencesAtom);
82 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
83 const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
84 const agentAwarenessPlatform = resolveAgentAwarenessPlatformPresentation(Platform.OS);
85 const agentAwarenessSubtitle =
86 Platform.OS === "android" && !agentAwarenessPushAvailable
87 ? "Install a newer app build to enable notifications"
88 : agentAwarenessPlatform.subtitle;
89 const insets = useSafeAreaInsets();
90 const navigation = useNavigation();
91 const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
92 const { savedConnectionsById } = useSavedRemoteConnections();
93 const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
94 const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
95 const liveActivityWriteInFlight = useRef(false);
96 const deviceRegistered = useDeviceRegistered();
97 const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
98 ? preferencesResult.value.liveActivitiesEnabled !== false
99 : true;
100 const canClearLiveActivitiesPreference =
101 AsyncResult.isSuccess(preferencesResult) &&
102 preferencesResult.value.liveActivitiesEnabled !== false;
103
104 const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
105 const environmentCount = connections.length;
106
107 const refreshNotifications = useCallback(async () => {
108 if (Platform.OS !== "ios" && Platform.OS !== "android") {
109 setNotificationStatus("unsupported");
110 return;
111 }
112 const result = await settlePromise(() => Notifications.getPermissionsAsync());
113 if (result._tag === "Failure") {
114 reportAtomCommandResult(result, { label: "notification permission refresh" });
115 setNotificationStatus("disabled");
116 return;
117 }
118 setNotificationStatus(result.value.granted ? "enabled" : "disabled");
119 }, []);
120
121 useEffect(() => {
122 void refreshNotifications();
123 const subscription = AppState.addEventListener("change", (state) => {
124 if (state === "active") void refreshNotifications();
125 });
126 return () => subscription.remove();
127 }, [refreshNotifications]);
128
129 useEffect(() => {
130 if (!isLoaded) {
131 setLiveActivityStatus("checking");
132 return;
133 }
134 if (!isSignedIn) {
135 setLiveActivityStatus("signed-out");
136 return;
137 }
138 if (!AsyncResult.isSuccess(preferencesResult)) {
139 if (AsyncResult.isFailure(preferencesResult)) {
140 reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });
141 setLiveActivityStatus("enabled");
142 } else {
143 setLiveActivityStatus("checking");
144 }
145 return;
146 }
147 setLiveActivityStatus(
148 preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",
149 );
150 }, [isLoaded, isSignedIn, preferencesResult]);
151
152 const requestNotifications = useCallback(async () => {
153 const result = await settleAsyncResult(() =>
154 runtime.runPromiseExit(
155 requestAgentNotificationPermission.pipe(
156 Effect.tap((permission) =>
157 permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
158 ),
159 ),
160 ),
161 );
162 if (result._tag === "Failure") {
163 if (!isAtomCommandInterrupted(result)) {
164 const error = squashAtomCommandFailure(result);
165 Alert.alert(
166 "Notifications unavailable",
167 error instanceof Error ? error.message : "Could not request notification permission.",
168 );
169 }
170 return;
171 }
172 if (result.value.type === "granted") {
173 setNotificationStatus("enabled");
174 // Permission alone is not enough: the switch stays off until the relay
175 // registration succeeds, so tell the user the truth about which happened.
176 if (getAgentAwarenessRegistrationStatus() === "registered") {
177 Alert.alert("Notifications enabled", "Agent notifications are enabled for this device.");
178 } else {
179 Alert.alert(
180 "Couldn't finish enabling notifications",
181 "Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.",
182 );
183 }
184 return;
185 }
186 if (result.value.type === "unsupported") {
187 setNotificationStatus("unsupported");
188 Alert.alert(
189 "Notifications unavailable",
190 "Agent notifications are unavailable on this platform.",
191 );
192 return;
193 }
194 setNotificationStatus("disabled");
195 if (result.value.canAskAgain) {
196 Alert.alert("Notifications disabled", "Notifications were not enabled.");
197 return;
198 }
199 Alert.alert(
200 "Notifications disabled",
201 "Notifications were denied for this app. Open Settings to enable them.",
202 [
203 { text: "Cancel", style: "cancel" },
204 { text: "Open Settings", onPress: () => void Linking.openSettings() },
205 ],
206 );
207 }, []);
208
209 const promptSignIn = useCallback(() => {
210 Alert.alert(
211 "Sign in to T3 Connect",
212 "Live Activity updates require T3 Connect so relay can deliver updates to this device.",
213 [
214 { text: "Cancel", style: "cancel" },
215 {
216 text: "Continue",
217 onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),
218 },
219 ],
220 );
221 }, [navigation]);
222
223 const linkEnvironments = useCallback(async () => {
224 if (!isSignedIn) {
225 promptSignIn();
226 return;
227 }
228
229 setLiveActivityStatus("linking");
230 if (Platform.OS === "android") {
231 const permission = await settleAsyncResult(() =>
232 runtime.runPromiseExit(requestAgentNotificationPermission),
233 );
234 if (permission._tag === "Failure") {
235 setLiveActivityStatus("disabled");
236 const error = squashAtomCommandFailure(permission);
237 Alert.alert(
238 "Ongoing activity unavailable",
239 error instanceof Error ? error.message : "Could not enable agent notifications.",
240 );
241 return;
242 }
243 if (permission.value.type !== "granted") {
244 setLiveActivityStatus("disabled");
245 Alert.alert(
246 "Notification permission needed",
247 "Enable notifications in system Settings to show ongoing agent activity.",
248 [
249 { text: "Cancel", style: "cancel" },
250 { text: "Open Settings", onPress: () => void Linking.openSettings() },
251 ],
252 );
253 return;
254 }
255 setNotificationStatus("enabled");
256 }
257 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
258 if (tokenResult._tag === "Failure") {
259 setLiveActivityStatus("disabled");
260 const error = squashAtomCommandFailure(tokenResult);
261 Alert.alert(
262 Platform.OS === "android" ? "Ongoing activity unavailable" : "Live Activities unavailable",
263 error instanceof Error ? error.message : "Could not enable agent activity updates.",
264 );
265 return;
266 }
267 if (!tokenResult.value) {
268 promptSignIn();
269 setLiveActivityStatus("signed-out");
270 return;
271 }
272
273 const updateResult = await settleAsyncResult(() =>
274 runtime.runPromiseExit(
275 setLiveActivityUpdatesEnabled({
276 canConfigureEnvironment: (environmentId) =>
277 readEnvironmentScope(environmentId, AuthRelayWriteScope),
278 enabled: true,
279 previousEnabled: liveActivitiesPreferenceEnabled,
280 clerkToken: tokenResult.value,
281 connections,
282 }),
283 ),
284 );
285 if (updateResult._tag === "Failure") {
286 setLiveActivityStatus("disabled");
287 if (!isAtomCommandInterrupted(updateResult)) {
288 const error = squashAtomCommandFailure(updateResult);
289 Alert.alert(
290 Platform.OS === "android"
291 ? "Ongoing activity unavailable"
292 : "Live Activities unavailable",
293 error instanceof Error ? error.message : "Could not enable agent activity updates.",
294 );
295 }
296 return;
297 }
298
299 savePreferences({ liveActivitiesEnabled: true });
300 refreshManagedRelayEnvironments();
301 setLiveActivityStatus("enabled");
302 // The environment link can succeed while this device's own registration
303 // (the push-to-start token the relay needs) has not — don't claim Live
304 // Activities are live until the device is actually registered.
305 if (getAgentAwarenessRegistrationStatus() === "registered") {
306 Alert.alert(
307 Platform.OS === "android" ? "Ongoing activity enabled" : "Live Activities enabled",
308 environmentCount > 0
309 ? "Agent activity updates are enabled for environments this connection can configure."
310 : "Agent activity updates are enabled. Add an environment to start receiving updates.",
311 );
312 } else {
313 Alert.alert(
314 "Couldn't finish enabling activity updates",
315 "This device could not be registered with T3 Connect, so activity updates won't appear yet. They'll start once registration succeeds.",
316 );
317 }
318 }, [
319 connections,
320 environmentCount,
321 getToken,
322 isSignedIn,
323 liveActivitiesPreferenceEnabled,
324 promptSignIn,
325 savePreferences,
326 ]);
327
328 const handleDeviceNotificationsChange = useCallback(
329 (enabled: boolean) => {
330 if (enabled) {
331 if (!isSignedIn) {
332 promptSignIn();
333 return;
334 }
335 void requestNotifications();
336 return;
337 }
338
339 Alert.alert(
340 "Disable notifications",
341 "Open system Settings to disable notifications for T3 Code.",
342 [
343 { text: "Cancel", style: "cancel" },
344 { text: "Open Settings", onPress: () => void Linking.openSettings() },
345 ],
346 );
347 },
348 [isSignedIn, promptSignIn, requestNotifications],
349 );
350
351 const handleLiveActivitiesChange = useCallback(
352 (enabled: boolean) => {
353 if (liveActivityWriteInFlight.current) return;
354 if (!enabled) {
355 liveActivityWriteInFlight.current = true;
356 setLiveActivityStatus("linking");
357 void (async () => {
358 try {
359 let token: string | null = null;
360 if (isSignedIn) {
361 const tokenResult = await settlePromise(() =>
362 getToken(resolveRelayClerkTokenOptions()),
363 );
364 if (tokenResult._tag === "Failure") {
365 setLiveActivityStatus("enabled");
366 reportAtomCommandResult(tokenResult, {
367 label: "live activity disable token lookup",
368 });
369 return;
370 }
371 token = tokenResult.value;
372 }
373
374 const updateResult = await settleAsyncResult(() =>
375 runtime.runPromiseExit(
376 setLiveActivityUpdatesEnabled({
377 canConfigureEnvironment: (environmentId) =>
378 readEnvironmentScope(environmentId, AuthRelayWriteScope),
379 enabled: false,
380 previousEnabled: liveActivitiesPreferenceEnabled,
381 clerkToken: token,
382 connections,
383 }),
384 ),
385 );
386 if (updateResult._tag === "Failure") {
387 setLiveActivityStatus(isSignedIn ? "enabled" : "signed-out");
388 reportAtomCommandResult(updateResult, {
389 label: "live activity disable",
390 });
391 return;
392 }
393 savePreferences({ liveActivitiesEnabled: false });
394 refreshManagedRelayEnvironments();
395 setLiveActivityStatus("disabled");
396 } finally {
397 liveActivityWriteInFlight.current = false;
398 }
399 })();
400 return;
401 }
402
403 if (!isSignedIn) {
404 promptSignIn();
405 return;
406 }
407
408 liveActivityWriteInFlight.current = true;
409 void linkEnvironments().finally(() => {
410 liveActivityWriteInFlight.current = false;
411 });
412 },
413 [
414 connections,
415 getToken,
416 isSignedIn,
417 linkEnvironments,
418 liveActivitiesPreferenceEnabled,
419 promptSignIn,
420 savePreferences,
421 ],
422 );
423
424 return (
425 <SettingsScreen title="Notifications">
426 <ScrollView
427 contentInsetAdjustmentBehavior="automatic"
428 showsVerticalScrollIndicator={false}
429 className="flex-1"
430 contentContainerClassName="gap-6 px-5 pt-4"
431 contentContainerStyle={{
432 paddingBottom: Math.max(insets.bottom, 18) + 18,
433 }}
434 >
435 <SettingsSection title="Agent activity">
436 <SettingsSwitchRow
437 icon="bell.badge"
438 label="Device Notifications"
439 disabled={
440 !agentAwarenessPlatform.supported ||
441 !agentAwarenessPushAvailable ||
442 notificationStatus === "checking" ||
443 notificationStatus === "unsupported"
444 }
445 subtitle={agentAwarenessSubtitle}
446 // Only reads as on when this device is actually registered with the
447 // relay; otherwise notifications cannot be delivered regardless of
448 // the local iOS permission.
449 value={
450 agentAwarenessPushAvailable && notificationStatus === "enabled" && deviceRegistered
451 }
452 onValueChange={handleDeviceNotificationsChange}
453 />
454 <SettingsSwitchRow
455 disabled={
456 !agentAwarenessPlatform.supported ||
457 !agentAwarenessPushAvailable ||
458 !isLoaded ||
459 liveActivityStatus === "checking" ||
460 liveActivityStatus === "linking"
461 }
462 icon="bolt.circle"
463 label={
464 Platform.OS === "android"
465 ? supportsAndroidLiveUpdateSettings()
466 ? "Agent Live Updates"
467 : "Ongoing Agent Activity"
468 : "Live Activity Updates"
469 }
470 subtitle={agentAwarenessSubtitle}
471 // Same gate: a saved preference is meaningless until the device
472 // registration the relay needs to push updates has succeeded.
473 value={
474 agentAwarenessPushAvailable &&
475 (liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&
476 deviceRegistered
477 }
478 onValueChange={handleLiveActivitiesChange}
479 />
480 {liveActivityStatus === "signed-out" && canClearLiveActivitiesPreference ? (
481 <SettingsRow
482 icon="bolt.circle"
483 label="Turn off Live Activity preference"
484 onPress={() => handleLiveActivitiesChange(false)}
485 />
486 ) : null}
487 {supportsAndroidLiveUpdateSettings() ? (
488 <SettingsRow
489 icon="bolt.circle"
490 label="Live Update Settings"
491 onPress={() => {
492 void openAndroidLiveUpdateSettings().catch(() => {
493 Alert.alert(
494 "Couldn't open Settings",
495 "Open Android Settings, select T3 Code, then enable Live Updates in Notifications.",
496 );
497 });
498 }}
499 />
500 ) : null}
501 </SettingsSection>
502 </ScrollView>
503 </SettingsScreen>
504 );
505}