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

SettingsNotificationsRouteScreen.tsx

614 lines22.7 KB

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