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