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

SettingsRouteScreen.tsx

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