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