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

SettingsNotificationsRouteScreen.tsx

470 lines16.9 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 { useEffect, 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 = Object.values(savedConnectionsById);
102 const environmentCount = connections.length;
103​
104 const refreshNotifications = 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 = 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 = () => {
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 };
217​
218 const linkEnvironments = 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​
315 const handleDeviceNotificationsChange = (enabled: boolean) => {
316 if (enabled) {
317 if (!isSignedIn) {
318 promptSignIn();
319 return;
320 }
321 void requestNotifications();
322 return;
323 }
324​
325 Dialog.alert(
326 "Disable notifications",
327 "Open system Settings to disable notifications for T3 Code.",
328 [
329 { text: "Cancel", style: "cancel" },
330 { text: "Open Settings", onPress: () => void Linking.openSettings() },
331 ],
332 );
333 };
334​
335 async function disableLiveActivities() {
336 let token: string | null = null;
337 if (isSignedIn) {
338 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
339 if (tokenResult._tag === "Failure") {
340 setLiveActivityStatus("enabled");
341 reportAtomCommandResult(tokenResult, {
342 label: "live activity disable token lookup",
343 });
344 return;
345 }
346 token = tokenResult.value;
347 }
348​
349 const updateResult = await settleAsyncResult(() =>
350 runtime.runPromiseExit(
351 setLiveActivityUpdatesEnabled({
352 canConfigureEnvironment: (environmentId) =>
353 readEnvironmentScope(environmentId, AuthRelayWriteScope),
354 enabled: false,
355 previousEnabled: liveActivitiesPreferenceEnabled,
356 clerkToken: token,
357 connections,
358 }),
359 ),
360 );
361 if (updateResult._tag === "Failure") {
362 setLiveActivityStatus(isSignedIn ? "enabled" : "signed-out");
363 reportAtomCommandResult(updateResult, {
364 label: "live activity disable",
365 });
366 return;
367 }
368 savePreferences({ liveActivitiesEnabled: false });
369 refreshManagedRelayEnvironments();
370 setLiveActivityStatus("disabled");
371 }
372​
373 // Both writers settle their own failures, so awaiting them never throws.
374 const handleLiveActivitiesChange = async (enabled: boolean) => {
375 if (liveActivityWriteInFlight.current) return;
376 if (!enabled) {
377 liveActivityWriteInFlight.current = true;
378 setLiveActivityStatus("linking");
379 await disableLiveActivities();
380 liveActivityWriteInFlight.current = false;
381 return;
382 }
383​
384 if (!isSignedIn) {
385 promptSignIn();
386 return;
387 }
388​
389 liveActivityWriteInFlight.current = true;
390 await linkEnvironments();
391 liveActivityWriteInFlight.current = false;
392 };
393​
394 return (
395 <SettingsScreen title="Notifications">
396 <ScrollView
397 contentInsetAdjustmentBehavior="automatic"
398 showsVerticalScrollIndicator={false}
399 className="flex-1"
400 contentContainerClassName="gap-6 px-5 pt-4"
401 contentContainerStyle={{
402 paddingBottom: Math.max(insets.bottom, 18) + 18,
403 }}
404 >
405 <SettingsSection title="Agent activity">
406 <SettingsSwitchRow
407 icon="bell.badge"
408 label="Device Notifications"
409 disabled={
410 !agentAwarenessPlatform.supported ||
411 !agentAwarenessPushAvailable ||
412 notificationStatus === "checking" ||
413 notificationStatus === "unsupported"
414 }
415 subtitle={agentAwarenessSubtitle}
416 value={
417 agentAwarenessPushAvailable && notificationStatus === "enabled" && deviceRegistered
418 }
419 onValueChange={handleDeviceNotificationsChange}
420 />
421 <SettingsSwitchRow
422 disabled={
423 !agentAwarenessPlatform.supported ||
424 !agentAwarenessPushAvailable ||
425 !isLoaded ||
426 liveActivityStatus === "checking" ||
427 liveActivityStatus === "linking"
428 }
429 icon="bolt.circle"
430 label={
431 Platform.OS === "android"
432 ? supportsAndroidLiveUpdateSettings()
433 ? "Agent Live Updates"
434 : "Ongoing Agent Activity"
435 : "Live Activity Updates"
436 }
437 subtitle={agentAwarenessSubtitle}
438 value={
439 agentAwarenessPushAvailable &&
440 (liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&
441 deviceRegistered
442 }
443 onValueChange={(enabled) => void handleLiveActivitiesChange(enabled)}
444 />
445 {liveActivityStatus === "signed-out" && canClearLiveActivitiesPreference ? (
446 <SettingsRow
447 icon="bolt.circle"
448 label="Turn off Live Activity preference"
449 onPress={() => void handleLiveActivitiesChange(false)}
450 />
451 ) : null}
452 {supportsAndroidLiveUpdateSettings() ? (
453 <SettingsRow
454 icon="bolt.circle"
455 label="Live Update Settings"
456 onPress={() => {
457 void openAndroidLiveUpdateSettings().catch(() => {
458 Dialog.alert(
459 "Couldn't open Settings",
460 "Open Android Settings, select T3 Code, then enable Live Updates in Notifications.",
461 );
462 });
463 }}
464 />
465 ) : null}
466 </SettingsSection>
467 </ScrollView>
468 </SettingsScreen>
469 );