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