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

SettingsNotificationsRouteScreen.tsx

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