Open History to see the last commit
1import { useAuth, useUser } from "@clerk/expo";
2import { useAtomSet, useAtomValue } from "@effect/atom-react";
3import Constants from "expo-constants";
4import * as Notifications from "expo-notifications";
5import * as Updates from "expo-updates";
6import { useNavigation } from "@react-navigation/native";
7import { NativeStackScreenOptions } from "../../native/StackHeader";
8import { SymbolView } from "../../components/AppSymbol";
9import * as Effect from "effect/Effect";
10import { AsyncResult } from "effect/unstable/reactivity";
11import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
12import { Alert, Linking, Platform, ScrollView, View } from "react-native";
13import { useSafeAreaInsets } from "react-native-safe-area-context";
14
15import {
16 isAtomCommandInterrupted,
17 reportAtomCommandResult,
18 settleAsyncResult,
19 settlePromise,
20 squashAtomCommandFailure,
21} from "@t3tools/client-runtime/state/runtime";
22import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
23import { AppText as Text } from "../../components/AppText";
24import { supportsAgentAwarenessPush } from "../agent-awareness/capabilities";
25import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences";
26import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";
27import {
28 getAgentAwarenessRegistrationStatus,
29 refreshAgentAwarenessRegistration,
30 subscribeAgentAwarenessRegistrationStatus,
31} from "../agent-awareness/remoteRegistration";
32import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
33import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
34import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
35import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
36import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
37import { runtime } from "../../lib/runtime";
38import { useThemeColor } from "../../lib/useThemeColor";
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";
44
45type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
46type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
47
48// Reflects whether the relay actually accepted this device's registration.
49// The notification and Live Activity switches are gated on this so they can
50// never read as enabled when the device cannot receive anything (e.g. the
51// registration request timed out).
52function useDeviceRegistered(): boolean {
53 const status = useSyncExternalStore(
54 subscribeAgentAwarenessRegistrationStatus,
55 getAgentAwarenessRegistrationStatus,
56 () => "unknown" as const,
57 );
58 return status === "registered";
59}
60
61export function SettingsRouteScreen() {
62 const navigation = useNavigation();
63
64 return (
65 <>
66 <WorkspaceSidebarToolbar />
67 {Platform.OS === "android" ? (
68 <>
69 {/* Android renders its own in-screen header instead of the native bar. */}
70 <NativeStackScreenOptions options={{ headerShown: false }} />
71 <AndroidScreenHeader title="Settings" onBack={() => navigation.goBack()} />
72 </>
73 ) : (
74 <NativeStackScreenOptions
75 options={{
76 unstable_headerRightItems:
77 Platform.OS === "ios"
78 ? () => [
79 withNativeGlassHeaderItem({
80 accessibilityLabel: "Close settings",
81 icon: { name: "xmark", type: "sfSymbol" } as const,
82 identifier: "settings-close",
83 label: "",
84 onPress: () => navigation.goBack(),
85 type: "button",
86 }),
87 ]
88 : undefined,
89 }}
90 />
91 )}
92 {hasCloudPublicConfig() ? <ConfiguredSettingsRouteScreen /> : <LocalSettingsRouteScreen />}
93 </>
94 );
95}
96
97function LocalSettingsRouteScreen() {
98 const insets = useSafeAreaInsets();
99 const { savedConnectionsById } = useSavedRemoteConnections();
100 const environmentCount = Object.keys(savedConnectionsById).length;
101
102 return (
103 <View collapsable={false} className="flex-1 bg-sheet">
104 <ScrollView
105 contentInsetAdjustmentBehavior="automatic"
106 showsVerticalScrollIndicator={false}
107 className="flex-1"
108 contentContainerClassName="gap-6 px-5 pt-4"
109 contentContainerStyle={{
110 paddingBottom: Math.max(insets.bottom, 18) + 18,
111 }}
112 >
113 <SettingsSection title="Configuration">
114 <SettingsRow
115 icon="desktopcomputer"
116 label="Environments"
117 value={`${environmentCount}`}
118 target="SettingsEnvironments"
119 />
120 </SettingsSection>
121
122 <SettingsSection title="Appearance">
123 <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
124 </SettingsSection>
125
126 <ArchivedThreadsSettingsSection />
127
128 <AppSettingsSection />
129 </ScrollView>
130 </View>
131 );
132}
133
134function ConfiguredSettingsRouteScreen() {
135 const preferencesResult = useAtomValue(mobilePreferencesAtom);
136 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
137 const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
138 const insets = useSafeAreaInsets();
139 const navigation = useNavigation();
140 const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
141 const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
142 const { user } = useUser();
143 const { savedConnectionsById } = useSavedRemoteConnections();
144 const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
145 const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
146 const deviceRegistered = useDeviceRegistered();
147 const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
148 ? preferencesResult.value.liveActivitiesEnabled !== false
149 : true;
150
151 const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
152 const environmentCount = connections.length;
153 const accountLabel = useMemo(() => {
154 if (!isLoaded) return "Checking";
155 if (!isSignedIn) return "Request access";
156 return user?.primaryEmailAddress?.emailAddress ?? "Signed in";
157 }, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]);
158
159 const refreshNotifications = useCallback(async () => {
160 if (process.env.EXPO_OS !== "ios") {
161 setNotificationStatus("unsupported");
162 return;
163 }
164 const result = await settlePromise(() => Notifications.getPermissionsAsync());
165 if (result._tag === "Failure") {
166 reportAtomCommandResult(result, { label: "notification permission refresh" });
167 setNotificationStatus("disabled");
168 return;
169 }
170 setNotificationStatus(result.value.granted ? "enabled" : "disabled");
171 }, []);
172
173 useEffect(() => {
174 void refreshNotifications();
175 }, [refreshNotifications]);
176
177 useEffect(() => {
178 if (!isLoaded) {
179 setLiveActivityStatus("checking");
180 return;
181 }
182 if (!isSignedIn) {
183 setLiveActivityStatus("signed-out");
184 return;
185 }
186 if (!AsyncResult.isSuccess(preferencesResult)) {
187 if (AsyncResult.isFailure(preferencesResult)) {
188 reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });
189 setLiveActivityStatus("enabled");
190 } else {
191 setLiveActivityStatus("checking");
192 }
193 return;
194 }
195 setLiveActivityStatus(
196 preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",
197 );
198 }, [isLoaded, isSignedIn, preferencesResult]);
199
200 const requestNotifications = useCallback(async () => {
201 const result = await settleAsyncResult(() =>
202 runtime.runPromiseExit(
203 requestAgentNotificationPermission.pipe(
204 Effect.tap((permission) =>
205 permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
206 ),
207 ),
208 ),
209 );
210 if (result._tag === "Failure") {
211 if (!isAtomCommandInterrupted(result)) {
212 const error = squashAtomCommandFailure(result);
213 Alert.alert(
214 "Notifications unavailable",
215 error instanceof Error ? error.message : "Could not request notification permission.",
216 );
217 }
218 return;
219 }
220 if (result.value.type === "granted") {
221 setNotificationStatus("enabled");
222 // Permission alone is not enough: the switch stays off until the relay
223 // registration succeeds, so tell the user the truth about which happened.
224 if (getAgentAwarenessRegistrationStatus() === "registered") {
225 Alert.alert(
226 "Notifications enabled",
227 "Live Activity notifications are enabled for this device.",
228 );
229 } else {
230 Alert.alert(
231 "Couldn't finish enabling notifications",
232 "Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.",
233 );
234 }
235 return;
236 }
237 if (result.value.type === "unsupported") {
238 setNotificationStatus("unsupported");
239 Alert.alert(
240 "Notifications unavailable",
241 "Live Activity notifications are only available on iOS.",
242 );
243 return;
244 }
245 setNotificationStatus("disabled");
246 if (result.value.canAskAgain) {
247 Alert.alert("Notifications disabled", "Notifications were not enabled.");
248 return;
249 }
250 Alert.alert(
251 "Notifications disabled",
252 "Notifications were denied for this app. Open Settings to enable them.",
253 [
254 { text: "Cancel", style: "cancel" },
255 { text: "Open Settings", onPress: () => void Linking.openSettings() },
256 ],
257 );
258 }, []);
259
260 const promptSignIn = useCallback(() => {
261 Alert.alert(
262 "Request T3 Connect access",
263 "Live Activity updates require approved T3 Connect access so relay can deliver updates to this device.",
264 [
265 { text: "Cancel", style: "cancel" },
266 {
267 text: "Continue",
268 onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsWaitlist" }),
269 },
270 ],
271 );
272 }, [navigation]);
273
274 const linkEnvironments = useCallback(async () => {
275 if (!isSignedIn) {
276 promptSignIn();
277 return;
278 }
279
280 setLiveActivityStatus("linking");
281 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
282 if (tokenResult._tag === "Failure") {
283 setLiveActivityStatus("disabled");
284 const error = squashAtomCommandFailure(tokenResult);
285 Alert.alert(
286 "Live Activities unavailable",
287 error instanceof Error ? error.message : "Could not enable Live Activity updates.",
288 );
289 return;
290 }
291 if (!tokenResult.value) {
292 promptSignIn();
293 setLiveActivityStatus("signed-out");
294 return;
295 }
296
297 const updateResult = await settleAsyncResult(() =>
298 runtime.runPromiseExit(
299 setLiveActivityUpdatesEnabled({
300 enabled: true,
301 previousEnabled: liveActivitiesPreferenceEnabled,
302 clerkToken: tokenResult.value,
303 connections,
304 }),
305 ),
306 );
307 if (updateResult._tag === "Failure") {
308 setLiveActivityStatus("disabled");
309 if (!isAtomCommandInterrupted(updateResult)) {
310 const error = squashAtomCommandFailure(updateResult);
311 Alert.alert(
312 "Live Activities unavailable",
313 error instanceof Error ? error.message : "Could not enable Live Activity updates.",
314 );
315 }
316 return;
317 }
318
319 savePreferences({ liveActivitiesEnabled: true });
320 refreshManagedRelayEnvironments();
321 setLiveActivityStatus("enabled");
322 // The environment link can succeed while this device's own registration
323 // (the push-to-start token the relay needs) has not — don't claim Live
324 // Activities are live until the device is actually registered.
325 if (getAgentAwarenessRegistrationStatus() === "registered") {
326 Alert.alert(
327 "Live Activities enabled",
328 environmentCount > 0
329 ? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
330 : "Live Activity updates are enabled. Add an environment to start receiving updates.",
331 );
332 } else {
333 Alert.alert(
334 "Couldn't finish enabling Live Activities",
335 "This device could not be registered with T3 Connect, so Live Activities won't appear yet. They'll start once registration succeeds.",
336 );
337 }
338 }, [
339 connections,
340 environmentCount,
341 getToken,
342 isSignedIn,
343 liveActivitiesPreferenceEnabled,
344 promptSignIn,
345 savePreferences,
346 ]);
347
348 const handleDeviceNotificationsChange = useCallback(
349 (enabled: boolean) => {
350 if (enabled) {
351 void requestNotifications();
352 return;
353 }
354
355 Alert.alert(
356 "Disable notifications",
357 "Notification permission is controlled by iOS. Open Settings to disable notifications for T3 Code.",
358 [
359 { text: "Cancel", style: "cancel" },
360 { text: "Open Settings", onPress: () => void Linking.openSettings() },
361 ],
362 );
363 },
364 [requestNotifications],
365 );
366
367 const handleLiveActivitiesChange = useCallback(
368 (enabled: boolean) => {
369 if (!enabled) {
370 setLiveActivityStatus("disabled");
371 void (async () => {
372 let token: string | null = null;
373 if (isSignedIn) {
374 const tokenResult = await settlePromise(() =>
375 getToken(resolveRelayClerkTokenOptions()),
376 );
377 if (tokenResult._tag === "Failure") {
378 reportAtomCommandResult(tokenResult, {
379 label: "live activity disable token lookup",
380 });
381 return;
382 }
383 token = tokenResult.value;
384 }
385
386 const updateResult = await settleAsyncResult(() =>
387 runtime.runPromiseExit(
388 setLiveActivityUpdatesEnabled({
389 enabled: false,
390 previousEnabled: liveActivitiesPreferenceEnabled,
391 clerkToken: token,
392 connections,
393 }),
394 ),
395 );
396 if (updateResult._tag === "Failure") {
397 setLiveActivityStatus("enabled");
398 reportAtomCommandResult(updateResult, {
399 label: "live activity disable",
400 });
401 return;
402 }
403 savePreferences({ liveActivitiesEnabled: false });
404 refreshManagedRelayEnvironments();
405 })();
406 return;
407 }
408
409 if (!isSignedIn) {
410 promptSignIn();
411 return;
412 }
413
414 void linkEnvironments();
415 },
416 [
417 connections,
418 getToken,
419 isSignedIn,
420 linkEnvironments,
421 liveActivitiesPreferenceEnabled,
422 promptSignIn,
423 savePreferences,
424 ],
425 );
426
427 const openAccount = useCallback(() => {
428 if (!isLoaded) return;
429 if (!isSignedIn) {
430 navigation.navigate("SettingsSheet", { screen: "SettingsWaitlist" });
431 return;
432 }
433 expandClerkSheet();
434 navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
435 }, [expandClerkSheet, isLoaded, isSignedIn, navigation]);
436
437 return (
438 <View collapsable={false} className="flex-1 bg-sheet">
439 <ScrollView
440 contentInsetAdjustmentBehavior="automatic"
441 showsVerticalScrollIndicator={false}
442 className="flex-1"
443 contentContainerClassName="gap-6 px-5 pt-4"
444 contentContainerStyle={{
445 paddingBottom: Math.max(insets.bottom, 18) + 18,
446 }}
447 >
448 <View className="gap-3">
449 <SettingsSection title="Account">
450 <SettingsRow
451 icon="person.crop.circle"
452 label="T3 Account"
453 value={accountLabel}
454 onPress={openAccount}
455 />
456 </SettingsSection>
457 <Text className="px-2 text-sm text-foreground-muted">
458 T3 Code works locally without signing in. Cloud features are optional.
459 </Text>
460 </View>
461
462 <SettingsSection title="Configuration">
463 <SettingsRow
464 icon="desktopcomputer"
465 label="Environments"
466 value={`${environmentCount}`}
467 target="SettingsEnvironments"
468 />
469 <SettingsSwitchRow
470 icon="bell.badge"
471 label="Device Notifications"
472 disabled={
473 !agentAwarenessPushAvailable ||
474 notificationStatus === "checking" ||
475 notificationStatus === "unsupported"
476 }
477 // Only reads as on when this device is actually registered with the
478 // relay; otherwise notifications cannot be delivered regardless of
479 // the local iOS permission.
480 value={
481 agentAwarenessPushAvailable && notificationStatus === "enabled" && deviceRegistered
482 }
483 onValueChange={handleDeviceNotificationsChange}
484 />
485 <SettingsSwitchRow
486 disabled={
487 !agentAwarenessPushAvailable ||
488 !isLoaded ||
489 liveActivityStatus === "checking" ||
490 liveActivityStatus === "linking"
491 }
492 icon="bolt.circle"
493 label="Live Activity Updates"
494 // Same gate: a saved preference is meaningless until the device
495 // registration the relay needs to push updates has succeeded.
496 value={
497 agentAwarenessPushAvailable &&
498 (liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&
499 deviceRegistered
500 }
501 onValueChange={handleLiveActivitiesChange}
502 />
503 </SettingsSection>
504
505 <SettingsSection title="Appearance">
506 <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
507 </SettingsSection>
508
509 <ArchivedThreadsSettingsSection />
510
511 <AppSettingsSection />
512 </ScrollView>
513 </View>
514 );
515}
516
517function AppSettingsSection() {
518 const icon = useThemeColor("--color-icon");
519
520 const version = Constants.expoConfig?.version ?? "0.0.0";
521 // Fall back to "production" to match resolveAppVariant in app.config.ts, so a
522 // missing variant never mislabels a production build as development.
523 const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
524 const variantLabel = variant === "production" ? "" : capitalize(variant);
525 const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
526 // Which JS is actually running: the bundle shipped in the binary, or an OTA
527 // update downloaded on top of it. Surfacing this makes "am I even on the
528 // right build?" answerable at a glance.
529 const bundleLabel = Updates.isEnabled
530 ? Updates.isEmbeddedLaunch
531 ? "Embedded"
532 : Updates.updateId
533 ? `OTA ${Updates.updateId.slice(0, 7)}`
534 : null
535 : null;
536
537 return (
538 <SettingsSection title="App">
539 <SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
540 <SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
541 <View className="flex-row items-center gap-4 p-4">
542 <SymbolView
543 name="info.circle"
544 size={22}
545 tintColor={icon}
546 type="monochrome"
547 weight="regular"
548 />
549 <Text className="flex-1 text-lg text-foreground">Version</Text>
550 <View className="items-end">
551 <Text className="text-lg text-foreground-muted">{versionLabel}</Text>
552 {bundleLabel ? (
553 <Text className="text-xs text-foreground-muted/70">{bundleLabel}</Text>
554 ) : null}
555 </View>
556 </View>
557 </SettingsSection>
558 );
559}
560
561function capitalize(value: string): string {
562 return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;
563}
564
565function ArchivedThreadsSettingsSection() {
566 return (
567 <SettingsSection title="Threads">
568 <SettingsRow icon="archivebox" label="Archived Threads" target="SettingsArchive" />
569 </SettingsSection>
570 );
571}