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