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

SettingsRouteScreen.tsx

675 lines23.3 KB

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, useRef, useState, useSyncExternalStore } from "react";
12import { Alert, Linking, Platform, Pressable, 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 { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
41import {
42 type AppUpdateCheckState,
43 registerHiddenUpdateTap,
44 runAppUpdateCheck,
45} from "../updates/app-updates";
46import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
47import { SettingsRow } from "./components/SettingsRow";
48import { SettingsSection } from "./components/SettingsSection";
49import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
50​
51type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
52type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
53​
54// Reflects whether the relay actually accepted this device's registration.
55// The notification and Live Activity switches are gated on this so they can
56// never read as enabled when the device cannot receive anything (e.g. the
57// registration request timed out).
58function useDeviceRegistered(): boolean {
59 const status = useSyncExternalStore(
60 subscribeAgentAwarenessRegistrationStatus,
61 getAgentAwarenessRegistrationStatus,
62 () => "unknown" as const,
63 );
64 return status === "registered";
66​
67export function SettingsRouteScreen() {
68 const navigation = useNavigation();
69​
70 return (
71 <>
72 <WorkspaceSidebarToolbar />
73 {Platform.OS === "android" ? (
74 <>
75 {/* Android renders its own in-screen header instead of the native bar. */}
76 <NativeStackScreenOptions options={{ headerShown: false }} />
77 <AndroidScreenHeader title="Settings" onBack={() => navigation.goBack()} />
78 </>
79 ) : (
80 <NativeStackScreenOptions
81 options={{
82 unstable_headerRightItems:
83 Platform.OS === "ios"
84 ? () => [
85 withNativeGlassHeaderItem({
86 accessibilityLabel: "Close settings",
87 icon: { name: "xmark", type: "sfSymbol" } as const,
88 identifier: "settings-close",
89 label: "",
90 onPress: () => navigation.goBack(),
91 type: "button",
92 }),
93 ]
94 : undefined,
95 }}
96 />
97 )}
98 {hasCloudPublicConfig() ? <ConfiguredSettingsRouteScreen /> : <LocalSettingsRouteScreen />}
99 </>
100 );
102​
103function LocalSettingsRouteScreen() {
104 const insets = useSafeAreaInsets();
105 const { savedConnectionsById } = useSavedRemoteConnections();
106 const environmentCount = Object.keys(savedConnectionsById).length;
107​
108 return (
109 <View collapsable={false} className="flex-1 bg-sheet">
110 <ScrollView
111 contentInsetAdjustmentBehavior="automatic"
112 showsVerticalScrollIndicator={false}
113 className="flex-1"
114 contentContainerClassName="gap-6 px-5 pt-4"
115 contentContainerStyle={{
116 paddingBottom: Math.max(insets.bottom, 18) + 18,
117 }}
118 >
119 <SettingsSection title="Configuration">
120 <SettingsRow
121 icon="desktopcomputer"
122 label="Environments"
123 value={`${environmentCount}`}
124 target="SettingsEnvironments"
125 />
126 </SettingsSection>
127​
128 <GeneralSettingsSection />
129​
130 <SettingsSection title="Appearance">
131 <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
132 </SettingsSection>
133​
134 <LegacySettingsSection />
135​
136 <ArchivedThreadsSettingsSection />
137​
138 <AppSettingsSection />
139 </ScrollView>
140 </View>
141 );
143​
144function ConfiguredSettingsRouteScreen() {
145 const preferencesResult = useAtomValue(mobilePreferencesAtom);
146 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
147 const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
148 const insets = useSafeAreaInsets();
149 const navigation = useNavigation();
150 const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
151 const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
152 const { user } = useUser();
153 const { savedConnectionsById } = useSavedRemoteConnections();
154 const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
155 const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
156 const deviceRegistered = useDeviceRegistered();
157 const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
158 ? preferencesResult.value.liveActivitiesEnabled !== false
159 : true;
160​
161 const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
162 const environmentCount = connections.length;
163 const accountLabel = useMemo(() => {
164 if (!isLoaded) return "Checking";
165 if (!isSignedIn) return "Sign in";
166 return user?.primaryEmailAddress?.emailAddress ?? "Signed in";
167 }, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]);
168​
169 const refreshNotifications = useCallback(async () => {
170 if (process.env.EXPO_OS !== "ios") {
171 setNotificationStatus("unsupported");
172 return;
173 }
174 const result = await settlePromise(() => Notifications.getPermissionsAsync());
175 if (result._tag === "Failure") {
176 reportAtomCommandResult(result, { label: "notification permission refresh" });
177 setNotificationStatus("disabled");
178 return;
179 }
180 setNotificationStatus(result.value.granted ? "enabled" : "disabled");
181 }, []);
182​
183 useEffect(() => {
184 void refreshNotifications();
185 }, [refreshNotifications]);
186​
187 useEffect(() => {
188 if (!isLoaded) {
189 setLiveActivityStatus("checking");
190 return;
191 }
192 if (!isSignedIn) {
193 setLiveActivityStatus("signed-out");
194 return;
195 }
196 if (!AsyncResult.isSuccess(preferencesResult)) {
197 if (AsyncResult.isFailure(preferencesResult)) {
198 reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });
199 setLiveActivityStatus("enabled");
200 } else {
201 setLiveActivityStatus("checking");
202 }
203 return;
204 }
205 setLiveActivityStatus(
206 preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",
207 );
208 }, [isLoaded, isSignedIn, preferencesResult]);
209​
210 const requestNotifications = useCallback(async () => {
211 const result = await settleAsyncResult(() =>
212 runtime.runPromiseExit(
213 requestAgentNotificationPermission.pipe(
214 Effect.tap((permission) =>
215 permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
216 ),
217 ),
218 ),
219 );
220 if (result._tag === "Failure") {
221 if (!isAtomCommandInterrupted(result)) {
222 const error = squashAtomCommandFailure(result);
223 Alert.alert(
224 "Notifications unavailable",
225 error instanceof Error ? error.message : "Could not request notification permission.",
226 );
227 }
228 return;
229 }
230 if (result.value.type === "granted") {
231 setNotificationStatus("enabled");
232 // Permission alone is not enough: the switch stays off until the relay
233 // registration succeeds, so tell the user the truth about which happened.
234 if (getAgentAwarenessRegistrationStatus() === "registered") {
235 Alert.alert(
236 "Notifications enabled",
237 "Live Activity notifications are enabled for this device.",
238 );
239 } else {
240 Alert.alert(
241 "Couldn't finish enabling notifications",
242 "Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.",
243 );
244 }
245 return;
246 }
247 if (result.value.type === "unsupported") {
248 setNotificationStatus("unsupported");
249 Alert.alert(
250 "Notifications unavailable",
251 "Live Activity notifications are only available on iOS.",
252 );
253 return;
254 }
255 setNotificationStatus("disabled");
256 if (result.value.canAskAgain) {
257 Alert.alert("Notifications disabled", "Notifications were not enabled.");
258 return;
259 }
260 Alert.alert(
261 "Notifications disabled",
262 "Notifications were denied for this app. Open Settings to enable them.",
263 [
264 { text: "Cancel", style: "cancel" },
265 { text: "Open Settings", onPress: () => void Linking.openSettings() },
266 ],
267 );
268 }, []);
269​
270 const promptSignIn = useCallback(() => {
271 Alert.alert(
272 "Sign in to T3 Connect",
273 "Live Activity updates require T3 Connect so relay can deliver updates to this device.",
274 [
275 { text: "Cancel", style: "cancel" },
276 {
277 text: "Continue",
278 onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),
279 },
280 ],
281 );
282 }, [navigation]);
283​
284 const linkEnvironments = useCallback(async () => {
285 if (!isSignedIn) {
286 promptSignIn();
287 return;
288 }
289​
290 setLiveActivityStatus("linking");
291 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
292 if (tokenResult._tag === "Failure") {
293 setLiveActivityStatus("disabled");
294 const error = squashAtomCommandFailure(tokenResult);
295 Alert.alert(
296 "Live Activities unavailable",
297 error instanceof Error ? error.message : "Could not enable Live Activity updates.",
298 );
299 return;
300 }
301 if (!tokenResult.value) {
302 promptSignIn();
303 setLiveActivityStatus("signed-out");
304 return;
305 }
306​
307 const updateResult = await settleAsyncResult(() =>
308 runtime.runPromiseExit(
309 setLiveActivityUpdatesEnabled({
310 enabled: true,
311 previousEnabled: liveActivitiesPreferenceEnabled,
312 clerkToken: tokenResult.value,
313 connections,
314 }),
315 ),
316 );
317 if (updateResult._tag === "Failure") {
318 setLiveActivityStatus("disabled");
319 if (!isAtomCommandInterrupted(updateResult)) {
320 const error = squashAtomCommandFailure(updateResult);
321 Alert.alert(
322 "Live Activities unavailable",
323 error instanceof Error ? error.message : "Could not enable Live Activity updates.",
324 );
325 }
326 return;
327 }
328​
329 savePreferences({ liveActivitiesEnabled: true });
330 refreshManagedRelayEnvironments();
331 setLiveActivityStatus("enabled");
332 // The environment link can succeed while this device's own registration
333 // (the push-to-start token the relay needs) has not — don't claim Live
334 // Activities are live until the device is actually registered.
335 if (getAgentAwarenessRegistrationStatus() === "registered") {
336 Alert.alert(
337 "Live Activities enabled",
338 environmentCount > 0
339 ? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
340 : "Live Activity updates are enabled. Add an environment to start receiving updates.",
341 );
342 } else {
343 Alert.alert(
344 "Couldn't finish enabling Live Activities",
345 "This device could not be registered with T3 Connect, so Live Activities won't appear yet. They'll start once registration succeeds.",
346 );
347 }
348 }, [
349 connections,
350 environmentCount,
351 getToken,
352 isSignedIn,
353 liveActivitiesPreferenceEnabled,
354 promptSignIn,
355 savePreferences,
356 ]);
357​
358 const handleDeviceNotificationsChange = useCallback(
359 (enabled: boolean) => {
360 if (enabled) {
361 void requestNotifications();
362 return;
363 }
364​
365 Alert.alert(
366 "Disable notifications",
367 "Notification permission is controlled by iOS. Open Settings to disable notifications for T3 Code.",
368 [
369 { text: "Cancel", style: "cancel" },
370 { text: "Open Settings", onPress: () => void Linking.openSettings() },
371 ],
372 );
373 },
374 [requestNotifications],
375 );
376​
377 const handleLiveActivitiesChange = useCallback(
378 (enabled: boolean) => {
379 if (!enabled) {
380 setLiveActivityStatus("disabled");
381 void (async () => {
382 let token: string | null = null;
383 if (isSignedIn) {
384 const tokenResult = await settlePromise(() =>
385 getToken(resolveRelayClerkTokenOptions()),
386 );
387 if (tokenResult._tag === "Failure") {
388 reportAtomCommandResult(tokenResult, {
389 label: "live activity disable token lookup",
390 });
391 return;
392 }
393 token = tokenResult.value;
394 }
395​
396 const updateResult = await settleAsyncResult(() =>
397 runtime.runPromiseExit(
398 setLiveActivityUpdatesEnabled({
399 enabled: false,
400 previousEnabled: liveActivitiesPreferenceEnabled,
401 clerkToken: token,
402 connections,
403 }),
404 ),
405 );
406 if (updateResult._tag === "Failure") {
407 setLiveActivityStatus("enabled");
408 reportAtomCommandResult(updateResult, {
409 label: "live activity disable",
410 });
411 return;
412 }
413 savePreferences({ liveActivitiesEnabled: false });
414 refreshManagedRelayEnvironments();
415 })();
416 return;
417 }
418​
419 if (!isSignedIn) {
420 promptSignIn();
421 return;
422 }
423​
424 void linkEnvironments();
425 },
426 [
427 connections,
428 getToken,
429 isSignedIn,
430 linkEnvironments,
431 liveActivitiesPreferenceEnabled,
432 promptSignIn,
433 savePreferences,
434 ],
435 );
436​
437 const openAccount = useCallback(() => {
438 if (!isLoaded) return;
439 if (!isSignedIn) {
440 expandClerkSheet();
441 navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
442 return;
443 }
444 expandClerkSheet();
445 navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
446 }, [expandClerkSheet, isLoaded, isSignedIn, navigation]);
447​
448 return (
449 <View collapsable={false} className="flex-1 bg-sheet">
450 <ScrollView
451 contentInsetAdjustmentBehavior="automatic"
452 showsVerticalScrollIndicator={false}
453 className="flex-1"
454 contentContainerClassName="gap-6 px-5 pt-4"
455 contentContainerStyle={{
456 paddingBottom: Math.max(insets.bottom, 18) + 18,
457 }}
458 >
459 <View className="gap-3">
460 <SettingsSection title="Account">
461 <SettingsRow
462 icon="person.crop.circle"
463 label="T3 Account"
464 value={accountLabel}
465 onPress={openAccount}
466 />
467 </SettingsSection>
468 <Text className="px-2 text-sm text-foreground-muted">
469 T3 Code works locally without signing in. Cloud features are optional.
470 </Text>
471 </View>
472​
473 <SettingsSection title="Configuration">
474 <SettingsRow
475 icon="desktopcomputer"
476 label="Environments"
477 value={`${environmentCount}`}
478 target="SettingsEnvironments"
479 />
480 <SettingsSwitchRow
481 icon="bell.badge"
482 label="Device Notifications"
483 disabled={
484 !agentAwarenessPushAvailable ||
485 notificationStatus === "checking" ||
486 notificationStatus === "unsupported"
487 }
488 // Only reads as on when this device is actually registered with the
489 // relay; otherwise notifications cannot be delivered regardless of
490 // the local iOS permission.
491 value={
492 agentAwarenessPushAvailable && notificationStatus === "enabled" && deviceRegistered
493 }
494 onValueChange={handleDeviceNotificationsChange}
495 />
496 <SettingsSwitchRow
497 disabled={
498 !agentAwarenessPushAvailable ||
499 !isLoaded ||
500 liveActivityStatus === "checking" ||
501 liveActivityStatus === "linking"
502 }
503 icon="bolt.circle"
504 label="Live Activity Updates"
505 // Same gate: a saved preference is meaningless until the device
506 // registration the relay needs to push updates has succeeded.
507 value={
508 agentAwarenessPushAvailable &&
509 (liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&
510 deviceRegistered
511 }
512 onValueChange={handleLiveActivitiesChange}
513 />
514 </SettingsSection>
515​
516 <GeneralSettingsSection />
517​
518 <SettingsSection title="Appearance">
519 <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
520 </SettingsSection>
521​
522 <LegacySettingsSection />
523​
524 <ArchivedThreadsSettingsSection />
525​
526 <AppSettingsSection />
527 </ScrollView>
528 </View>
529 );
531​
532function GeneralSettingsSection() {
533 return (
534 <SettingsSection title="General">
535 <SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
536 <SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
537 </SettingsSection>
538 );
540​
541/**
542 * Device-local legacy toggles. Mobile has no client-settings sync, so this is
543 * the counterpart of web's Settings → General → Legacy features backed by
544 * mobile preferences.
545 */
546function LegacySettingsSection() {
547 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
548 const threadListV2Enabled = useThreadListV2Enabled();
549​
550 return (
551 <View className="gap-3">
552 <SettingsSection title="Legacy">
553 <SettingsSwitchRow
554 icon="sidebar.left"
555 label="Legacy Thread List"
556 value={!threadListV2Enabled}
557 onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })}
558 />
559 </SettingsSection>
560 <Text className="px-2 text-sm text-foreground-muted">
561 Brings back the original grouped thread list. The default list is flat, in creation order:
562 active work renders as cards; settled threads collapse to compact rows.
563 </Text>
564 </View>
565 );
567​
568function AppSettingsSection() {
569 const icon = useThemeColor("--color-icon");
570 const [updateState, setUpdateState] = useState<AppUpdateCheckState>("idle");
571 const updateInFlight = useRef(false);
572 const hiddenUpdateTapCount = useRef(0);
573​
574 const version = Constants.expoConfig?.version ?? "0.0.0";
575 // Fall back to "production" to match resolveAppVariant in app.config.ts, so a
576 // missing variant never mislabels a production build as development.
577 const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
578 const variantLabel = variant === "production" ? "" : capitalize(variant);
579 const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
580 const busy =
581 updateState === "checking" || updateState === "downloading" || updateState === "restarting";
582​
583 // "Up to date" is a transient acknowledgement, not a state worth persisting —
584 // return the version row to its normal, deliberately quiet state.
585 useEffect(() => {
586 if (updateState !== "current") return;
587 const timer = setTimeout(() => setUpdateState("idle"), 3000);
588 return () => clearTimeout(timer);
589 }, [updateState]);
590​
591 const checkForUpdate = useCallback(async () => {
592 // `disabled={busy}` only takes effect on the next render, so two taps in the
593 // same frame would both get through. The ref closes that window.
594 if (updateInFlight.current) return;
595 updateInFlight.current = true;
596 try {
597 await runAppUpdateCheck({
598 onFailure: (message) => Alert.alert("Update failed", message),
599 onStateChange: setUpdateState,
600 });
601 } finally {
602 updateInFlight.current = false;
603 }
604 }, []);
605​
606 const handleVersionPress = useCallback(() => {
607 if (!Updates.isEnabled || updateInFlight.current) return;
608 const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
609 hiddenUpdateTapCount.current = tap.nextCount;
610 if (tap.shouldCheck) {
611 void checkForUpdate();
612 }
613 }, [checkForUpdate]);
614​
615 const statusLabel =
616 updateState === "checking"
617 ? "Checking…"
618 : updateState === "downloading"
619 ? "Downloading…"
620 : updateState === "restarting"
621 ? "Restarting…"
622 : updateState === "current"
623 ? "Up to date"
624 : null;
625​
626 const versionRow = (
627 <View className="flex-row items-center gap-4 p-4">
628 <SymbolView
629 name="info.circle"
630 size={22}
631 tintColor={icon}
632 type="monochrome"
633 weight="regular"
634 />
635 <Text className="flex-1 text-lg text-foreground">Version</Text>
636 <View className="items-end">
637 <Text className="text-lg text-foreground-muted">{versionLabel}</Text>
638 {statusLabel ? (
639 <Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>
640 ) : null}
641 </View>
642 </View>
643 );
644​
645 return (
646 <SettingsSection title="App">
647 <SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
648 <SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
649 {Updates.isEnabled ? (
650 <Pressable
651 accessibilityLabel={`Version ${versionLabel}`}
652 accessibilityRole="text"
653 disabled={busy}
654 onPress={handleVersionPress}
655 >
656 {versionRow}
657 </Pressable>
658 ) : (
659 versionRow
660 )}
661 </SettingsSection>
662 );
664​
665function capitalize(value: string): string {
666 return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;
668​
669function ArchivedThreadsSettingsSection() {
670 return (
671 <SettingsSection title="Threads">
672 <SettingsRow icon="archivebox" label="Archived Threads" target="SettingsArchive" />
673 </SettingsSection>
674 );