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

SettingsRouteScreen.tsx

749 lines25.8 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 * as Updates from "expo-updates";
6import { useNavigation } from "@react-navigation/native";
7import { NativeStackScreenOptions } from "../../native/StackHeader";
8import { SymbolView } from "../../components/AppSymbol";
9import * as Effect from "effect/Effect";
10import { AsyncResult } from "effect/unstable/reactivity";
11import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
12import {
13 ActivityIndicator,
14 Alert,
15 Linking,
16 Platform,
17 Pressable,
18 ScrollView,
19 View,
20} from "react-native";
21import { useSafeAreaInsets } from "react-native-safe-area-context";
22​
23import {
24 type AtomCommandResult,
25 isAtomCommandInterrupted,
26 reportAtomCommandResult,
27 settleAsyncResult,
28 settlePromise,
29 squashAtomCommandFailure,
30} from "@t3tools/client-runtime/state/runtime";
31import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
32import { AppText as Text } from "../../components/AppText";
33import { supportsAgentAwarenessPush } from "../agent-awareness/capabilities";
34import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences";
35import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";
36import {
37 getAgentAwarenessRegistrationStatus,
38 refreshAgentAwarenessRegistration,
39 subscribeAgentAwarenessRegistrationStatus,
40} from "../agent-awareness/remoteRegistration";
41import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
42import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
43import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
44import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
45import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
46import { runtime } from "../../lib/runtime";
47import { useThemeColor } from "../../lib/useThemeColor";
48import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
49import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
50import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
51import { SettingsRow } from "./components/SettingsRow";
52import { SettingsSection } from "./components/SettingsSection";
53import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
54​
55type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
56type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
57​
58// Reflects whether the relay actually accepted this device's registration.
59// The notification and Live Activity switches are gated on this so they can
60// never read as enabled when the device cannot receive anything (e.g. the
61// registration request timed out).
62function useDeviceRegistered(): boolean {
63 const status = useSyncExternalStore(
64 subscribeAgentAwarenessRegistrationStatus,
65 getAgentAwarenessRegistrationStatus,
66 () => "unknown" as const,
67 );
68 return status === "registered";
70​
71export function SettingsRouteScreen() {
72 const navigation = useNavigation();
73​
74 return (
75 <>
76 <WorkspaceSidebarToolbar />
77 {Platform.OS === "android" ? (
78 <>
79 {/* Android renders its own in-screen header instead of the native bar. */}
80 <NativeStackScreenOptions options={{ headerShown: false }} />
81 <AndroidScreenHeader title="Settings" onBack={() => navigation.goBack()} />
82 </>
83 ) : (
84 <NativeStackScreenOptions
85 options={{
86 unstable_headerRightItems:
87 Platform.OS === "ios"
88 ? () => [
89 withNativeGlassHeaderItem({
90 accessibilityLabel: "Close settings",
91 icon: { name: "xmark", type: "sfSymbol" } as const,
92 identifier: "settings-close",
93 label: "",
94 onPress: () => navigation.goBack(),
95 type: "button",
96 }),
97 ]
98 : undefined,
99 }}
100 />
101 )}
102 {hasCloudPublicConfig() ? <ConfiguredSettingsRouteScreen /> : <LocalSettingsRouteScreen />}
103 </>
104 );
106​
107function LocalSettingsRouteScreen() {
108 const insets = useSafeAreaInsets();
109 const { savedConnectionsById } = useSavedRemoteConnections();
110 const environmentCount = Object.keys(savedConnectionsById).length;
111​
112 return (
113 <View collapsable={false} className="flex-1 bg-sheet">
114 <ScrollView
115 contentInsetAdjustmentBehavior="automatic"
116 showsVerticalScrollIndicator={false}
117 className="flex-1"
118 contentContainerClassName="gap-6 px-5 pt-4"
119 contentContainerStyle={{
120 paddingBottom: Math.max(insets.bottom, 18) + 18,
121 }}
122 >
123 <SettingsSection title="Configuration">
124 <SettingsRow
125 icon="desktopcomputer"
126 label="Environments"
127 value={`${environmentCount}`}
128 target="SettingsEnvironments"
129 />
130 </SettingsSection>
131​
132 <GeneralSettingsSection />
133​
134 <SettingsSection title="Appearance">
135 <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
136 </SettingsSection>
137​
138 <BetaSettingsSection />
139​
140 <ArchivedThreadsSettingsSection />
141​
142 <AppSettingsSection />
143 </ScrollView>
144 </View>
145 );
147​
148function ConfiguredSettingsRouteScreen() {
149 const preferencesResult = useAtomValue(mobilePreferencesAtom);
150 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
151 const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
152 const insets = useSafeAreaInsets();
153 const navigation = useNavigation();
154 const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
155 const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
156 const { user } = useUser();
157 const { savedConnectionsById } = useSavedRemoteConnections();
158 const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
159 const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
160 const deviceRegistered = useDeviceRegistered();
161 const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
162 ? preferencesResult.value.liveActivitiesEnabled !== false
163 : true;
164​
165 const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
166 const environmentCount = connections.length;
167 const accountLabel = useMemo(() => {
168 if (!isLoaded) return "Checking";
169 if (!isSignedIn) return "Sign in";
170 return user?.primaryEmailAddress?.emailAddress ?? "Signed in";
171 }, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]);
172​
173 const refreshNotifications = useCallback(async () => {
174 if (process.env.EXPO_OS !== "ios") {
175 setNotificationStatus("unsupported");
176 return;
177 }
178 const result = await settlePromise(() => Notifications.getPermissionsAsync());
179 if (result._tag === "Failure") {
180 reportAtomCommandResult(result, { label: "notification permission refresh" });
181 setNotificationStatus("disabled");
182 return;
183 }
184 setNotificationStatus(result.value.granted ? "enabled" : "disabled");
185 }, []);
186​
187 useEffect(() => {
188 void refreshNotifications();
189 }, [refreshNotifications]);
190​
191 useEffect(() => {
192 if (!isLoaded) {
193 setLiveActivityStatus("checking");
194 return;
195 }
196 if (!isSignedIn) {
197 setLiveActivityStatus("signed-out");
198 return;
199 }
200 if (!AsyncResult.isSuccess(preferencesResult)) {
201 if (AsyncResult.isFailure(preferencesResult)) {
202 reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });
203 setLiveActivityStatus("enabled");
204 } else {
205 setLiveActivityStatus("checking");
206 }
207 return;
208 }
209 setLiveActivityStatus(
210 preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",
211 );
212 }, [isLoaded, isSignedIn, preferencesResult]);
213​
214 const requestNotifications = useCallback(async () => {
215 const result = await settleAsyncResult(() =>
216 runtime.runPromiseExit(
217 requestAgentNotificationPermission.pipe(
218 Effect.tap((permission) =>
219 permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
220 ),
221 ),
222 ),
223 );
224 if (result._tag === "Failure") {
225 if (!isAtomCommandInterrupted(result)) {
226 const error = squashAtomCommandFailure(result);
227 Alert.alert(
228 "Notifications unavailable",
229 error instanceof Error ? error.message : "Could not request notification permission.",
230 );
231 }
232 return;
233 }
234 if (result.value.type === "granted") {
235 setNotificationStatus("enabled");
236 // Permission alone is not enough: the switch stays off until the relay
237 // registration succeeds, so tell the user the truth about which happened.
238 if (getAgentAwarenessRegistrationStatus() === "registered") {
239 Alert.alert(
240 "Notifications enabled",
241 "Live Activity notifications are enabled for this device.",
242 );
243 } else {
244 Alert.alert(
245 "Couldn't finish enabling notifications",
246 "Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.",
247 );
248 }
249 return;
250 }
251 if (result.value.type === "unsupported") {
252 setNotificationStatus("unsupported");
253 Alert.alert(
254 "Notifications unavailable",
255 "Live Activity notifications are only available on iOS.",
256 );
257 return;
258 }
259 setNotificationStatus("disabled");
260 if (result.value.canAskAgain) {
261 Alert.alert("Notifications disabled", "Notifications were not enabled.");
262 return;
263 }
264 Alert.alert(
265 "Notifications disabled",
266 "Notifications were denied for this app. Open Settings to enable them.",
267 [
268 { text: "Cancel", style: "cancel" },
269 { text: "Open Settings", onPress: () => void Linking.openSettings() },
270 ],
271 );
272 }, []);
273​
274 const promptSignIn = useCallback(() => {
275 Alert.alert(
276 "Sign in to T3 Connect",
277 "Live Activity updates require T3 Connect so relay can deliver updates to this device.",
278 [
279 { text: "Cancel", style: "cancel" },
280 {
281 text: "Continue",
282 onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),
283 },
284 ],
285 );
286 }, [navigation]);
287​
288 const linkEnvironments = useCallback(async () => {
289 if (!isSignedIn) {
290 promptSignIn();
291 return;
292 }
293​
294 setLiveActivityStatus("linking");
295 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
296 if (tokenResult._tag === "Failure") {
297 setLiveActivityStatus("disabled");
298 const error = squashAtomCommandFailure(tokenResult);
299 Alert.alert(
300 "Live Activities unavailable",
301 error instanceof Error ? error.message : "Could not enable Live Activity updates.",
302 );
303 return;
304 }
305 if (!tokenResult.value) {
306 promptSignIn();
307 setLiveActivityStatus("signed-out");
308 return;
309 }
310​
311 const updateResult = await settleAsyncResult(() =>
312 runtime.runPromiseExit(
313 setLiveActivityUpdatesEnabled({
314 enabled: true,
315 previousEnabled: liveActivitiesPreferenceEnabled,
316 clerkToken: tokenResult.value,
317 connections,
318 }),
319 ),
320 );
321 if (updateResult._tag === "Failure") {
322 setLiveActivityStatus("disabled");
323 if (!isAtomCommandInterrupted(updateResult)) {
324 const error = squashAtomCommandFailure(updateResult);
325 Alert.alert(
326 "Live Activities unavailable",
327 error instanceof Error ? error.message : "Could not enable Live Activity updates.",
328 );
329 }
330 return;
331 }
332​
333 savePreferences({ liveActivitiesEnabled: true });
334 refreshManagedRelayEnvironments();
335 setLiveActivityStatus("enabled");
336 // The environment link can succeed while this device's own registration
337 // (the push-to-start token the relay needs) has not — don't claim Live
338 // Activities are live until the device is actually registered.
339 if (getAgentAwarenessRegistrationStatus() === "registered") {
340 Alert.alert(
341 "Live Activities enabled",
342 environmentCount > 0
343 ? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
344 : "Live Activity updates are enabled. Add an environment to start receiving updates.",
345 );
346 } else {
347 Alert.alert(
348 "Couldn't finish enabling Live Activities",
349 "This device could not be registered with T3 Connect, so Live Activities won't appear yet. They'll start once registration succeeds.",
350 );
351 }
352 }, [
353 connections,
354 environmentCount,
355 getToken,
356 isSignedIn,
357 liveActivitiesPreferenceEnabled,
358 promptSignIn,
359 savePreferences,
360 ]);
361​
362 const handleDeviceNotificationsChange = useCallback(
363 (enabled: boolean) => {
364 if (enabled) {
365 void requestNotifications();
366 return;
367 }
368​
369 Alert.alert(
370 "Disable notifications",
371 "Notification permission is controlled by iOS. Open Settings to disable notifications for T3 Code.",
372 [
373 { text: "Cancel", style: "cancel" },
374 { text: "Open Settings", onPress: () => void Linking.openSettings() },
375 ],
376 );
377 },
378 [requestNotifications],
379 );
380​
381 const handleLiveActivitiesChange = useCallback(
382 (enabled: boolean) => {
383 if (!enabled) {
384 setLiveActivityStatus("disabled");
385 void (async () => {
386 let token: string | null = null;
387 if (isSignedIn) {
388 const tokenResult = await settlePromise(() =>
389 getToken(resolveRelayClerkTokenOptions()),
390 );
391 if (tokenResult._tag === "Failure") {
392 reportAtomCommandResult(tokenResult, {
393 label: "live activity disable token lookup",
394 });
395 return;
396 }
397 token = tokenResult.value;
398 }
399​
400 const updateResult = await settleAsyncResult(() =>
401 runtime.runPromiseExit(
402 setLiveActivityUpdatesEnabled({
403 enabled: false,
404 previousEnabled: liveActivitiesPreferenceEnabled,
405 clerkToken: token,
406 connections,
407 }),
408 ),
409 );
410 if (updateResult._tag === "Failure") {
411 setLiveActivityStatus("enabled");
412 reportAtomCommandResult(updateResult, {
413 label: "live activity disable",
414 });
415 return;
416 }
417 savePreferences({ liveActivitiesEnabled: false });
418 refreshManagedRelayEnvironments();
419 })();
420 return;
421 }
422​
423 if (!isSignedIn) {
424 promptSignIn();
425 return;
426 }
427​
428 void linkEnvironments();
429 },
430 [
431 connections,
432 getToken,
433 isSignedIn,
434 linkEnvironments,
435 liveActivitiesPreferenceEnabled,
436 promptSignIn,
437 savePreferences,
438 ],
439 );
440​
441 const openAccount = useCallback(() => {
442 if (!isLoaded) return;
443 if (!isSignedIn) {
444 expandClerkSheet();
445 navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
446 return;
447 }
448 expandClerkSheet();
449 navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
450 }, [expandClerkSheet, isLoaded, isSignedIn, navigation]);
451​
452 return (
453 <View collapsable={false} className="flex-1 bg-sheet">
454 <ScrollView
455 contentInsetAdjustmentBehavior="automatic"
456 showsVerticalScrollIndicator={false}
457 className="flex-1"
458 contentContainerClassName="gap-6 px-5 pt-4"
459 contentContainerStyle={{
460 paddingBottom: Math.max(insets.bottom, 18) + 18,
461 }}
462 >
463 <View className="gap-3">
464 <SettingsSection title="Account">
465 <SettingsRow
466 icon="person.crop.circle"
467 label="T3 Account"
468 value={accountLabel}
469 onPress={openAccount}
470 />
471 </SettingsSection>
472 <Text className="px-2 text-sm text-foreground-muted">
473 T3 Code works locally without signing in. Cloud features are optional.
474 </Text>
475 </View>
476​
477 <SettingsSection title="Configuration">
478 <SettingsRow
479 icon="desktopcomputer"
480 label="Environments"
481 value={`${environmentCount}`}
482 target="SettingsEnvironments"
483 />
484 <SettingsSwitchRow
485 icon="bell.badge"
486 label="Device Notifications"
487 disabled={
488 !agentAwarenessPushAvailable ||
489 notificationStatus === "checking" ||
490 notificationStatus === "unsupported"
491 }
492 // Only reads as on when this device is actually registered with the
493 // relay; otherwise notifications cannot be delivered regardless of
494 // the local iOS permission.
495 value={
496 agentAwarenessPushAvailable && notificationStatus === "enabled" && deviceRegistered
497 }
498 onValueChange={handleDeviceNotificationsChange}
499 />
500 <SettingsSwitchRow
501 disabled={
502 !agentAwarenessPushAvailable ||
503 !isLoaded ||
504 liveActivityStatus === "checking" ||
505 liveActivityStatus === "linking"
506 }
507 icon="bolt.circle"
508 label="Live Activity Updates"
509 // Same gate: a saved preference is meaningless until the device
510 // registration the relay needs to push updates has succeeded.
511 value={
512 agentAwarenessPushAvailable &&
513 (liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&
514 deviceRegistered
515 }
516 onValueChange={handleLiveActivitiesChange}
517 />
518 </SettingsSection>
519​
520 <GeneralSettingsSection />
521​
522 <SettingsSection title="Appearance">
523 <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
524 </SettingsSection>
525​
526 <BetaSettingsSection />
527​
528 <ArchivedThreadsSettingsSection />
529​
530 <AppSettingsSection />
531 </ScrollView>
532 </View>
533 );
535​
536function GeneralSettingsSection() {
537 const preferencesResult = useAtomValue(mobilePreferencesAtom);
538 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
539 const projectGroupingEnabled = AsyncResult.isSuccess(preferencesResult)
540 ? preferencesResult.value.projectGroupingEnabled !== false
541 : true;
542​
543 return (
544 <SettingsSection title="General">
545 <SettingsSwitchRow
546 icon="folder"
547 label="Project Grouping"
548 value={projectGroupingEnabled}
549 onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
550 />
551 </SettingsSection>
552 );
554​
555/**
556 * Device-local beta toggles. Mobile has no client-settings sync, so this is
557 * the counterpart of web's Settings → Beta backed by mobile preferences.
558 */
559function BetaSettingsSection() {
560 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
561 const threadListV2Enabled = useThreadListV2Enabled();
562​
563 return (
564 <View className="gap-3">
565 <SettingsSection title="Beta">
566 <SettingsSwitchRow
567 icon="sidebar.left"
568 label="Thread List v2"
569 value={threadListV2Enabled}
570 onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
571 />
572 </SettingsSection>
573 <Text className="px-2 text-sm text-foreground-muted">
574 One flat thread list in creation order. Active work renders as cards; settled threads
575 collapse to compact rows. Switch back any time.
576 </Text>
577 </View>
578 );
580​
581type UpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
582​
583function AppSettingsSection() {
584 const icon = useThemeColor("--color-icon");
585 const [updateState, setUpdateState] = useState<UpdateCheckState>("idle");
586 const updateInFlight = useRef(false);
587​
588 const version = Constants.expoConfig?.version ?? "0.0.0";
589 // Fall back to "production" to match resolveAppVariant in app.config.ts, so a
590 // missing variant never mislabels a production build as development.
591 const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
592 const variantLabel = variant === "production" ? "" : capitalize(variant);
593 const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
594 // Which JS is actually running: the bundle shipped in the binary, or an OTA
595 // update downloaded on top of it. Surfacing this makes "am I even on the
596 // right build?" answerable at a glance.
597 const bundleLabel = Updates.isEnabled
598 ? Updates.isEmbeddedLaunch
599 ? "Embedded"
600 : Updates.updateId
601 ? `OTA ${Updates.updateId.slice(0, 7)}`
602 : null
603 : null;
604​
605 const busy =
606 updateState === "checking" || updateState === "downloading" || updateState === "restarting";
607​
608 // "Up to date" is a transient acknowledgement, not a state worth persisting —
609 // drop back to the bundle label so the row keeps answering "what am I running?".
610 useEffect(() => {
611 if (updateState !== "current") return;
612 const timer = setTimeout(() => setUpdateState("idle"), 3000);
613 return () => clearTimeout(timer);
614 }, [updateState]);
615​
616 const checkForUpdate = useCallback(async () => {
617 // `disabled={busy}` only takes effect on the next render, so two taps in the
618 // same frame would both get through. The ref closes that window.
619 if (updateInFlight.current) return;
620 updateInFlight.current = true;
621 try {
622 await runUpdateCheck(setUpdateState);
623 } finally {
624 updateInFlight.current = false;
625 }
626 }, []);
627​
628 const statusLabel =
629 updateState === "checking"
630 ? "Checking…"
631 : updateState === "downloading"
632 ? "Downloading…"
633 : updateState === "restarting"
634 ? "Restarting…"
635 : updateState === "current"
636 ? "Up to date"
637 : bundleLabel;
638​
639 const versionRow = (
640 <View className="flex-row items-center gap-4 p-4">
641 <SymbolView
642 name="info.circle"
643 size={22}
644 tintColor={icon}
645 type="monochrome"
646 weight="regular"
647 />
648 <Text className="flex-1 text-lg text-foreground">Version</Text>
649 <View className="items-end">
650 <Text className="text-lg text-foreground-muted">{versionLabel}</Text>
651 {statusLabel ? (
652 <Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>
653 ) : null}
654 </View>
655 {Updates.isEnabled ? (
656 <View className="w-[22px] items-center">
657 {busy ? (
658 <ActivityIndicator color={icon} size="small" />
659 ) : (
660 <SymbolView
661 name="arrow.clockwise"
662 size={18}
663 tintColor={icon}
664 type="monochrome"
665 weight="semibold"
666 />
667 )}
668 </View>
669 ) : null}
670 </View>
671 );
672​
673 return (
674 <SettingsSection title="App">
675 <SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
676 <SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
677 {Updates.isEnabled ? (
678 <Pressable
679 accessibilityLabel="Check for updates"
680 accessibilityRole="button"
681 disabled={busy}
682 onPress={() => void checkForUpdate()}
683 >
684 {versionRow}
685 </Pressable>
686 ) : (
687 versionRow
688 )}
689 </SettingsSection>
690 );
692​
693async function runUpdateCheck(setUpdateState: (state: UpdateCheckState) => void): Promise<void> {
694 setUpdateState("checking");
695 const check = await settlePromise(() => Updates.checkForUpdateAsync());
696 if (check._tag === "Failure") {
697 reportUpdateFailure(check, "Could not check for updates.");
698 setUpdateState("idle");
699 return;
700 }
701 // A rollback directive (`eas update:rollback`) arrives as isAvailable: false
702 // with isRollBackToEmbedded: true — there is nothing newer to install, but the
703 // running OTA still has to be dropped for the embedded bundle.
704 if (!check.value.isAvailable && !check.value.isRollBackToEmbedded) {
705 setUpdateState("current");
706 return;
707 }
708​
709 setUpdateState("downloading");
710 const fetched = await settlePromise(() => Updates.fetchUpdateAsync());
711 if (fetched._tag === "Failure") {
712 reportUpdateFailure(fetched, "Could not download the update.");
713 setUpdateState("idle");
714 return;
715 }
716 // isNew is always false for a rollback, so it can't be the sole gate here either.
717 if (!fetched.value.isNew && !fetched.value.isRollBackToEmbedded) {
718 setUpdateState("current");
719 return;
720 }
721​
722 setUpdateState("restarting");
723 // reloadAsync never resolves on success — the JS context is torn down — so
724 // reaching the failure branch below is the only way this returns.
725 const reloaded = await settlePromise(() => Updates.reloadAsync());
726 if (reloaded._tag === "Failure") {
727 reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.");
728 setUpdateState("idle");
729 }
731​
732function reportUpdateFailure(result: AtomCommandResult<unknown, unknown>, fallback: string): void {
733 reportAtomCommandResult(result, { label: "app update check" });
734 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
735 const error = squashAtomCommandFailure(result);
736 Alert.alert("Update failed", error instanceof Error ? error.message : fallback);
738​
739function capitalize(value: string): string {
740 return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;
742​
743function ArchivedThreadsSettingsSection() {
744 return (
745 <SettingsSection title="Threads">
746 <SettingsRow icon="archivebox" label="Archived Threads" target="SettingsArchive" />
747 </SettingsSection>
748 );