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