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