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