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

SettingsRouteScreen.tsx

826 lines29.1 KB

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