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