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, AppTextInput as TextInput } 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 { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
37import { serverEnvironment } from "../../state/server";
38import { useAtomCommand } from "../../state/use-atom-command";
39import { useEnvironments } from "../../state/environments";
40import {
41 DEFAULT_SERVER_SETTINGS,
42 MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
43 MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
44 type ServerSettingsPatch,
45} from "@t3tools/contracts";
46import {
47 filterSharedServerPatch,
48 findSharedSettingsMismatches,
49 pickSharedServerSettings,
50 supportsSharedSettingsSync,
51} from "@t3tools/client-runtime/state/shared-settings";
52import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
53import {
54 type AppUpdateCheckState,
55 isAppUpdateCheckAvailable,
56 registerHiddenUpdateTap,
57 runAppUpdateCheck,
58} from "../updates/app-updates";
59import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
60import { SettingsRow } from "./components/SettingsRow";
61import { SettingsSection } from "./components/SettingsSection";
62import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
63import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
64
65type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
66type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
67
68// Reflects whether the relay actually accepted this device's registration.
69// The notification and Live Activity switches are gated on this so they can
70// never read as enabled when the device cannot receive anything (e.g. the
71// registration request timed out).
72function useDeviceRegistered(): boolean {
73 const status = useSyncExternalStore(
74 subscribeAgentAwarenessRegistrationStatus,
75 getAgentAwarenessRegistrationStatus,
76 () => "unknown" as const,
77 );
78 return status === "registered";
79}
80
81export function SettingsRouteScreen() {
82 const navigation = useNavigation();
83
84 return (
85 <>
86 <WorkspaceSidebarToolbar />
87 {Platform.OS === "android" ? (
88 <>
89 {/* Android renders its own in-screen header instead of the native bar. */}
90 <NativeStackScreenOptions options={{ headerShown: false }} />
91 <AndroidScreenHeader title="Settings" onBack={() => navigation.goBack()} />
92 </>
93 ) : (
94 <NativeStackScreenOptions
95 options={{
96 unstable_headerRightItems:
97 Platform.OS === "ios"
98 ? () => [
99 withNativeGlassHeaderItem({
100 accessibilityLabel: "Close settings",
101 icon: { name: "xmark", type: "sfSymbol" } as const,
102 identifier: "settings-close",
103 label: "",
104 onPress: () => navigation.goBack(),
105 type: "button",
106 }),
107 ]
108 : undefined,
109 }}
110 />
111 )}
112 {hasCloudPublicConfig() ? <ConfiguredSettingsRouteScreen /> : <LocalSettingsRouteScreen />}
113 </>
114 );
115}
116
117function LocalSettingsRouteScreen() {
118 const insets = useSafeAreaInsets();
119 const { savedConnectionsById } = useSavedRemoteConnections();
120 const environmentCount = Object.keys(savedConnectionsById).length;
121
122 return (
123 <View collapsable={false} className="flex-1 bg-sheet">
124 <ScrollView
125 contentInsetAdjustmentBehavior="automatic"
126 showsVerticalScrollIndicator={false}
127 className="flex-1"
128 contentContainerClassName="gap-6 px-5 pt-4"
129 contentContainerStyle={{
130 paddingBottom: Math.max(insets.bottom, 18) + 18,
131 }}
132 >
133 <SettingsSection title="Configuration">
134 <SettingsRow
135 icon="desktopcomputer"
136 label="Environments"
137 value={`${environmentCount}`}
138 target="SettingsEnvironments"
139 />
140 </SettingsSection>
141
142 <GeneralSettingsSection />
143
144 <SettingsSection title="Appearance">
145 <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
146 </SettingsSection>
147
148 <LegacySettingsSection />
149
150 <ArchivedThreadsSettingsSection />
151
152 <AppSettingsSection />
153 </ScrollView>
154 </View>
155 );
156}
157
158function ConfiguredSettingsRouteScreen() {
159 const preferencesResult = useAtomValue(mobilePreferencesAtom);
160 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
161 const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
162 const agentAwarenessPlatform = resolveAgentAwarenessPlatformPresentation(Platform.OS);
163 const insets = useSafeAreaInsets();
164 const navigation = useNavigation();
165 const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
166 const { user } = useUser();
167 const { savedConnectionsById } = useSavedRemoteConnections();
168 const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
169 const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
170 const deviceRegistered = useDeviceRegistered();
171 const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
172 ? preferencesResult.value.liveActivitiesEnabled !== false
173 : true;
174
175 const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
176 const environmentCount = connections.length;
177 const accountLabel = useMemo(() => {
178 if (!isLoaded) return "Checking";
179 if (!isSignedIn) return "Sign in";
180 return user?.primaryEmailAddress?.emailAddress ?? "Signed in";
181 }, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]);
182
183 const refreshNotifications = useCallback(async () => {
184 if (process.env.EXPO_OS !== "ios") {
185 setNotificationStatus("unsupported");
186 return;
187 }
188 const result = await settlePromise(() => Notifications.getPermissionsAsync());
189 if (result._tag === "Failure") {
190 reportAtomCommandResult(result, { label: "notification permission refresh" });
191 setNotificationStatus("disabled");
192 return;
193 }
194 setNotificationStatus(result.value.granted ? "enabled" : "disabled");
195 }, []);
196
197 useEffect(() => {
198 void refreshNotifications();
199 }, [refreshNotifications]);
200
201 useEffect(() => {
202 if (!isLoaded) {
203 setLiveActivityStatus("checking");
204 return;
205 }
206 if (!isSignedIn) {
207 setLiveActivityStatus("signed-out");
208 return;
209 }
210 if (!AsyncResult.isSuccess(preferencesResult)) {
211 if (AsyncResult.isFailure(preferencesResult)) {
212 reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });
213 setLiveActivityStatus("enabled");
214 } else {
215 setLiveActivityStatus("checking");
216 }
217 return;
218 }
219 setLiveActivityStatus(
220 preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",
221 );
222 }, [isLoaded, isSignedIn, preferencesResult]);
223
224 const requestNotifications = useCallback(async () => {
225 const result = await settleAsyncResult(() =>
226 runtime.runPromiseExit(
227 requestAgentNotificationPermission.pipe(
228 Effect.tap((permission) =>
229 permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
230 ),
231 ),
232 ),
233 );
234 if (result._tag === "Failure") {
235 if (!isAtomCommandInterrupted(result)) {
236 const error = squashAtomCommandFailure(result);
237 Alert.alert(
238 "Notifications unavailable",
239 error instanceof Error ? error.message : "Could not request notification permission.",
240 );
241 }
242 return;
243 }
244 if (result.value.type === "granted") {
245 setNotificationStatus("enabled");
246 // Permission alone is not enough: the switch stays off until the relay
247 // registration succeeds, so tell the user the truth about which happened.
248 if (getAgentAwarenessRegistrationStatus() === "registered") {
249 Alert.alert(
250 "Notifications enabled",
251 "Live Activity notifications are enabled for this device.",
252 );
253 } else {
254 Alert.alert(
255 "Couldn't finish enabling notifications",
256 "Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.",
257 );
258 }
259 return;
260 }
261 if (result.value.type === "unsupported") {
262 setNotificationStatus("unsupported");
263 Alert.alert(
264 "Notifications unavailable",
265 "Live Activity notifications are only available on iOS.",
266 );
267 return;
268 }
269 setNotificationStatus("disabled");
270 if (result.value.canAskAgain) {
271 Alert.alert("Notifications disabled", "Notifications were not enabled.");
272 return;
273 }
274 Alert.alert(
275 "Notifications disabled",
276 "Notifications were denied for this app. Open Settings to enable them.",
277 [
278 { text: "Cancel", style: "cancel" },
279 { text: "Open Settings", onPress: () => void Linking.openSettings() },
280 ],
281 );
282 }, []);
283
284 const promptSignIn = useCallback(() => {
285 Alert.alert(
286 "Sign in to T3 Connect",
287 "Live Activity updates require T3 Connect so relay can deliver updates to this device.",
288 [
289 { text: "Cancel", style: "cancel" },
290 {
291 text: "Continue",
292 onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),
293 },
294 ],
295 );
296 }, [navigation]);
297
298 const linkEnvironments = useCallback(async () => {
299 if (!isSignedIn) {
300 promptSignIn();
301 return;
302 }
303
304 setLiveActivityStatus("linking");
305 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
306 if (tokenResult._tag === "Failure") {
307 setLiveActivityStatus("disabled");
308 const error = squashAtomCommandFailure(tokenResult);
309 Alert.alert(
310 "Live Activities unavailable",
311 error instanceof Error ? error.message : "Could not enable Live Activity updates.",
312 );
313 return;
314 }
315 if (!tokenResult.value) {
316 promptSignIn();
317 setLiveActivityStatus("signed-out");
318 return;
319 }
320
321 const updateResult = await settleAsyncResult(() =>
322 runtime.runPromiseExit(
323 setLiveActivityUpdatesEnabled({
324 enabled: true,
325 previousEnabled: liveActivitiesPreferenceEnabled,
326 clerkToken: tokenResult.value,
327 connections,
328 }),
329 ),
330 );
331 if (updateResult._tag === "Failure") {
332 setLiveActivityStatus("disabled");
333 if (!isAtomCommandInterrupted(updateResult)) {
334 const error = squashAtomCommandFailure(updateResult);
335 Alert.alert(
336 "Live Activities unavailable",
337 error instanceof Error ? error.message : "Could not enable Live Activity updates.",
338 );
339 }
340 return;
341 }
342
343 savePreferences({ liveActivitiesEnabled: true });
344 refreshManagedRelayEnvironments();
345 setLiveActivityStatus("enabled");
346 // The environment link can succeed while this device's own registration
347 // (the push-to-start token the relay needs) has not — don't claim Live
348 // Activities are live until the device is actually registered.
349 if (getAgentAwarenessRegistrationStatus() === "registered") {
350 Alert.alert(
351 "Live Activities enabled",
352 environmentCount > 0
353 ? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
354 : "Live Activity updates are enabled. Add an environment to start receiving updates.",
355 );
356 } else {
357 Alert.alert(
358 "Couldn't finish enabling Live Activities",
359 "This device could not be registered with T3 Connect, so Live Activities won't appear yet. They'll start once registration succeeds.",
360 );
361 }
362 }, [
363 connections,
364 environmentCount,
365 getToken,
366 isSignedIn,
367 liveActivitiesPreferenceEnabled,
368 promptSignIn,
369 savePreferences,
370 ]);
371
372 const handleDeviceNotificationsChange = useCallback(
373 (enabled: boolean) => {
374 if (enabled) {
375 void requestNotifications();
376 return;
377 }
378
379 Alert.alert(
380 "Disable notifications",
381 "Notification permission is controlled by iOS. Open Settings to disable notifications for T3 Code.",
382 [
383 { text: "Cancel", style: "cancel" },
384 { text: "Open Settings", onPress: () => void Linking.openSettings() },
385 ],
386 );
387 },
388 [requestNotifications],
389 );
390
391 const handleLiveActivitiesChange = useCallback(
392 (enabled: boolean) => {
393 if (!enabled) {
394 setLiveActivityStatus("disabled");
395 void (async () => {
396 let token: string | null = null;
397 if (isSignedIn) {
398 const tokenResult = await settlePromise(() =>
399 getToken(resolveRelayClerkTokenOptions()),
400 );
401 if (tokenResult._tag === "Failure") {
402 reportAtomCommandResult(tokenResult, {
403 label: "live activity disable token lookup",
404 });
405 return;
406 }
407 token = tokenResult.value;
408 }
409
410 const updateResult = await settleAsyncResult(() =>
411 runtime.runPromiseExit(
412 setLiveActivityUpdatesEnabled({
413 enabled: false,
414 previousEnabled: liveActivitiesPreferenceEnabled,
415 clerkToken: token,
416 connections,
417 }),
418 ),
419 );
420 if (updateResult._tag === "Failure") {
421 setLiveActivityStatus("enabled");
422 reportAtomCommandResult(updateResult, {
423 label: "live activity disable",
424 });
425 return;
426 }
427 savePreferences({ liveActivitiesEnabled: false });
428 refreshManagedRelayEnvironments();
429 })();
430 return;
431 }
432
433 if (!isSignedIn) {
434 promptSignIn();
435 return;
436 }
437
438 void linkEnvironments();
439 },
440 [
441 connections,
442 getToken,
443 isSignedIn,
444 linkEnvironments,
445 liveActivitiesPreferenceEnabled,
446 promptSignIn,
447 savePreferences,
448 ],
449 );
450
451 const openAccount = useCallback(() => {
452 if (!isLoaded) return;
453 navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
454 }, [isLoaded, navigation]);
455
456 return (
457 <View collapsable={false} className="flex-1 bg-sheet">
458 <ScrollView
459 contentInsetAdjustmentBehavior="automatic"
460 showsVerticalScrollIndicator={false}
461 className="flex-1"
462 contentContainerClassName="gap-6 px-5 pt-4"
463 contentContainerStyle={{
464 paddingBottom: Math.max(insets.bottom, 18) + 18,
465 }}
466 >
467 <View className="gap-3">
468 <SettingsSection title="Account">
469 <SettingsRow
470 icon="person.crop.circle"
471 label="T3 Account"
472 value={accountLabel}
473 onPress={openAccount}
474 />
475 </SettingsSection>
476 <Text className="px-2 text-sm text-foreground-muted">
477 T3 Code works locally without signing in. Cloud features are optional.
478 </Text>
479 </View>
480
481 <SettingsSection title="Configuration">
482 <SettingsRow
483 icon="desktopcomputer"
484 label="Environments"
485 value={`${environmentCount}`}
486 target="SettingsEnvironments"
487 />
488 <SettingsSwitchRow
489 icon="bell.badge"
490 label="Device Notifications"
491 disabled={
492 !agentAwarenessPlatform.supported ||
493 !agentAwarenessPushAvailable ||
494 notificationStatus === "checking" ||
495 notificationStatus === "unsupported"
496 }
497 subtitle={agentAwarenessPlatform.subtitle}
498 // Only reads as on when this device is actually registered with the
499 // relay; otherwise notifications cannot be delivered regardless of
500 // the local iOS permission.
501 value={
502 agentAwarenessPushAvailable && notificationStatus === "enabled" && deviceRegistered
503 }
504 onValueChange={handleDeviceNotificationsChange}
505 />
506 <SettingsSwitchRow
507 disabled={
508 !agentAwarenessPlatform.supported ||
509 !agentAwarenessPushAvailable ||
510 !isLoaded ||
511 liveActivityStatus === "checking" ||
512 liveActivityStatus === "linking"
513 }
514 icon="bolt.circle"
515 label="Live Activity Updates"
516 subtitle={agentAwarenessPlatform.subtitle}
517 // Same gate: a saved preference is meaningless until the device
518 // registration the relay needs to push updates has succeeded.
519 value={
520 agentAwarenessPushAvailable &&
521 (liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&
522 deviceRegistered
523 }
524 onValueChange={handleLiveActivitiesChange}
525 />
526 </SettingsSection>
527
528 <GeneralSettingsSection />
529
530 <SettingsSection title="Appearance">
531 <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
532 </SettingsSection>
533
534 <LegacySettingsSection />
535
536 <ArchivedThreadsSettingsSection />
537
538 <AppSettingsSection />
539 </ScrollView>
540 </View>
541 );
542}
543
544function GeneralSettingsSection() {
545 return (
546 <SettingsSection title="General">
547 <SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
548 <AutoSettleSettingsRows />
549 <SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
550 </SettingsSection>
551 );
552}
553
554const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_SERVER_SETTINGS.sidebarAutoSettleAfterDays ?? 3;
555
556/**
557 * Auto-settlement is a user preference that every server has to hold. Mobile
558 * has no primary environment, so the first eligible sync target provides the
559 * reference value. Edits fan out to every eligible target, and a mismatch row
560 * lets the user push the reference out.
561 */
562function AutoSettleSettingsRows() {
563 const { environments } = useEnvironments();
564 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
565 label: "server settings update",
566 reportFailure: true,
567 });
568
569 const syncTargets = environments.filter(supportsSharedSettingsSync);
570 const reference = syncTargets[0] ?? null;
571 const referenceSettings = reference?.serverConfig?.settings ?? null;
572
573 const [daysDraft, setDaysDraft] = useState<string | null>(null);
574
575 if (reference === null || referenceSettings === null) {
576 return null;
577 }
578
579 const writeToAll = (patch: ServerSettingsPatch) => {
580 for (const environment of syncTargets) {
581 void updateSettings({ environmentId: environment.environmentId, input: { patch } });
582 }
583 };
584
585 const mismatches = findSharedSettingsMismatches({
586 primaryEnvironmentId: reference.environmentId,
587 primarySettings: referenceSettings,
588 primaryCapabilities: reference.serverConfig?.environment.capabilities,
589 environments: environments.map((environment) => ({
590 environmentId: environment.environmentId,
591 label: environment.label,
592 syncEligible: supportsSharedSettingsSync(environment),
593 settings: environment.serverConfig?.settings ?? null,
594 capabilities: environment.serverConfig?.environment.capabilities,
595 })),
596 });
597
598 const afterDays = referenceSettings.sidebarAutoSettleAfterDays;
599 const commitDays = () => {
600 const draft = (daysDraft ?? "").trim();
601 setDaysDraft(null);
602 // Whole-string check so "3.5" and "3days" are rejected instead of
603 // silently becoming 3 on every eligible sync target.
604 const parsed = /^\d+$/.test(draft) ? Number(draft) : Number.NaN;
605 if (
606 Number.isInteger(parsed) &&
607 parsed >= MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS &&
608 parsed <= MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS &&
609 parsed !== afterDays
610 ) {
611 writeToAll({ sidebarAutoSettleAfterDays: parsed });
612 }
613 };
614
615 return (
616 <>
617 <SettingsSwitchRow
618 icon="arrow.triangle.branch"
619 label="Auto-settle merged threads"
620 value={referenceSettings.sidebarAutoSettleOnMerge}
621 onValueChange={(value) => writeToAll({ sidebarAutoSettleOnMerge: value })}
622 />
623 <SettingsSwitchRow
624 icon="clock"
625 label="Auto-settle inactive threads"
626 subtitle={afterDays === null ? undefined : `After ${afterDays} days without activity`}
627 value={afterDays !== null}
628 onValueChange={(value) =>
629 writeToAll({ sidebarAutoSettleAfterDays: value ? AUTO_SETTLE_DEFAULT_DAYS : null })
630 }
631 />
632 {afterDays !== null ? (
633 <View className="flex-row items-center gap-4 border-t border-border-subtle p-4">
634 <Text className="flex-1 text-lg text-foreground">Days before auto-settle</Text>
635 <TextInput
636 className="min-h-10 w-20 rounded-xl px-3 py-2 text-center text-base"
637 keyboardType="number-pad"
638 returnKeyType="done"
639 value={daysDraft ?? String(afterDays)}
640 onChangeText={setDaysDraft}
641 onBlur={commitDays}
642 onSubmitEditing={commitDays}
643 accessibilityLabel="Days before auto-settle"
644 />
645 </View>
646 ) : null}
647 {mismatches.length > 0 ? (
648 <View className="flex-row items-center gap-4 border-t border-border-subtle p-4">
649 <View className="min-w-0 flex-1">
650 <Text className="text-lg text-foreground">Settings differ</Text>
651 <Text className="text-sm text-foreground-muted">
652 {mismatches.map((mismatch) => mismatch.label).join(", ")}
653 </Text>
654 </View>
655 <Pressable
656 accessibilityRole="button"
657 onPress={() => {
658 const patch = pickSharedServerSettings(
659 referenceSettings,
660 reference.serverConfig?.environment.capabilities,
661 );
662 for (const mismatch of mismatches) {
663 const target = environments.find(
664 (candidate) => candidate.environmentId === mismatch.environmentId,
665 );
666 void updateSettings({
667 environmentId: mismatch.environmentId,
668 input: {
669 patch: filterSharedServerPatch(
670 patch,
671 target?.serverConfig?.environment.capabilities,
672 ),
673 },
674 });
675 }
676 }}
677 className="rounded-full bg-subtle px-4 py-2 active:opacity-70"
678 >
679 <Text className="text-base font-t3-medium text-foreground">Apply to all</Text>
680 </Pressable>
681 </View>
682 ) : null}
683 </>
684 );
685}
686
687/**
688 * Device-local legacy toggles. Mobile has no client-settings sync, so this is
689 * the counterpart of web's Settings → General → Legacy features backed by
690 * mobile preferences.
691 */
692function LegacySettingsSection() {
693 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
694 const preferences = useAtomValue(mobilePreferencesAtom);
695 const threadListV2Enabled = useThreadListV2Enabled();
696 const planModeEnabled =
697 AsyncResult.isSuccess(preferences) && preferences.value.planModeEnabled === true;
698
699 return (
700 <View className="gap-3">
701 <SettingsSection title="Legacy">
702 <SettingsSwitchRow
703 icon="sidebar.left"
704 label="Legacy Thread List"
705 value={!threadListV2Enabled}
706 onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })}
707 />
708 <SettingsSwitchRow
709 icon="hammer"
710 label="Plan Mode"
711 value={planModeEnabled}
712 onValueChange={(value) => savePreferences({ planModeEnabled: value })}
713 />
714 </SettingsSection>
715 <Text className="px-2 text-sm text-foreground-muted">
716 Opt into retired interfaces kept for compatibility. Plan Mode restores the Build/Plan
717 control; otherwise every task runs in Build mode.
718 </Text>
719 </View>
720 );
721}
722
723function AppSettingsSection() {
724 const [updateState, setUpdateState] = useState<AppUpdateCheckState>("idle");
725 const updateInFlight = useRef(false);
726 const hiddenUpdateTapCount = useRef(0);
727
728 const version = Constants.expoConfig?.version ?? "0.0.0";
729 // Fall back to "production" to match resolveAppVariant in app.config.ts, so a
730 // missing variant never mislabels a production build as development.
731 const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
732 const variantLabel = variant === "production" ? "" : capitalize(variant);
733 const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
734 const updateCheckAvailable = isAppUpdateCheckAvailable();
735 const busy =
736 updateState === "checking" || updateState === "downloading" || updateState === "restarting";
737
738 // "Up to date" is a transient acknowledgement, not a state worth persisting —
739 // return the version row to its normal, deliberately quiet state.
740 useEffect(() => {
741 if (updateState !== "current") return;
742 const timer = setTimeout(() => setUpdateState("idle"), 3000);
743 return () => clearTimeout(timer);
744 }, [updateState]);
745
746 const checkForUpdate = useCallback(async () => {
747 // `disabled={busy}` only takes effect on the next render, so two taps in the
748 // same frame would both get through. The ref closes that window.
749 if (updateInFlight.current) return;
750 updateInFlight.current = true;
751 try {
752 // The user asked for this restart by tapping the version row, so it may
753 // apply immediately instead of prompting.
754 await runAppUpdateCheck({
755 applyMode: "immediate",
756 onFailure: (message) => Alert.alert("Update failed", message),
757 onStateChange: setUpdateState,
758 });
759 } finally {
760 updateInFlight.current = false;
761 }
762 }, []);
763
764 const handleVersionPress = useCallback(() => {
765 if (!updateCheckAvailable || updateInFlight.current) return;
766 const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
767 hiddenUpdateTapCount.current = tap.nextCount;
768 if (tap.shouldCheck) {
769 void checkForUpdate();
770 }
771 }, [checkForUpdate, updateCheckAvailable]);
772
773 const statusLabel =
774 updateState === "checking"
775 ? "Checking…"
776 : updateState === "downloading"
777 ? "Downloading…"
778 : // "ready" appears only when this check joined an in-flight background-mode
779 // check; that download installs at the next backgrounding.
780 updateState === "ready"
781 ? "Update ready"
782 : updateState === "restarting"
783 ? "Restarting…"
784 : updateState === "current"
785 ? "Up to date"
786 : null;
787
788 const versionRow = (
789 <View className="flex-row items-center gap-4 p-4">
790 <SymbolView
791 name="info.circle"
792 size={22}
793 tintColorClassName={"accent-icon"}
794 type="monochrome"
795 weight="regular"
796 />
797 <Text className="flex-1 text-lg text-foreground">Version</Text>
798 <View className="items-end">
799 <Text className="text-lg text-foreground-muted">{versionLabel}</Text>
800 {statusLabel ? (
801 <Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>
802 ) : null}
803 </View>
804 </View>
805 );
806
807 return (
808 <SettingsSection title="App">
809 <SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
810 <SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
811 {updateCheckAvailable ? (
812 <Pressable
813 accessibilityLabel={`Version ${versionLabel}`}
814 accessibilityRole="text"
815 disabled={busy}
816 onPress={handleVersionPress}
817 >
818 {versionRow}
819 </Pressable>
820 ) : (
821 versionRow
822 )}
823 </SettingsSection>
824 );
825}
826
827function capitalize(value: string): string {
828 return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;
829}
830
831function ArchivedThreadsSettingsSection() {
832 return (
833 <SettingsSection title="Threads">
834 <SettingsRow icon="archivebox" label="Archived Threads" target="SettingsArchive" />
835 </SettingsSection>
836 );
837}