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

SettingsNotificationsRouteScreen.tsx

495 lines17.7 KB

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