Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SettingsNotificationsRouteScreen.tsx

499 lines18.1 KB

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