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

SettingsRouteScreen.tsx

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