Skip to content

Commit b66655f

Browse files
refactor(mobile): settings permission and update checks without sync effects
The microphone and notifications settings screens each subscribed to AppState in an effect to re-read a system permission, the notifications screen copied auth/preference state into Live Activity state in a second effect, and both environment update checks kept an AbortController in a ref with an unmount-only effect to cancel the release lookup. - permissionStatusAtom: one atom helper that reads a permission when first observed and again on every foreground; requests write their outcome to it. Microphone and notification screens use it. - Live Activity status is derived in render from auth and preferences, with an explicit override for an in-flight or failed write that lapses when the state it was based on changes. - environmentReleaseCheckAtom: the release lookup runs as an Atom.fn, so leaving the screen interrupts it and aborts the fetch, and the 20s timeout reports "Checking for updates timed out. Try again." instead of a raw abort error. Effects: OutdatedServerUpdateSection 1 -> 0, SettingsEnvironmentDetail 1 -> 0, SettingsMicrophone 1 -> 0, SettingsNotifications 2 -> 0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent edf5a24 commit b66655f

8 files changed

Lines changed: 357 additions & 127 deletions

‎apps/mobile/src/features/settings/OutdatedServerUpdateSection.tsx‎

Lines changed: 21 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import { useAtomValue } from "@effect/atom-react";
2-
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
1+
import { useAtom, useAtomValue } from "@effect/atom-react";
2+
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
33
import type { EnvironmentId } from "@t3tools/contracts";
44
import { AsyncResult } from "effect/reactivity";
5-
import { useEffect, useRef, useState } from "react";
5+
import { useState } from "react";
66
import { View } from "react-native";
77

88
import { AppText as Text } from "../../components/ui/AppText";
@@ -15,7 +15,11 @@ import {
1515
import { useAtomCommand } from "../../state/use-atom-command";
1616
import { SettingsActionRow } from "./components/SettingsActionRow";
1717
import { SettingsSection } from "./components/SettingsSection";
18-
import { findEnvironmentUpdate } from "./environment-maintenance";
18+
import {
19+
environmentReleaseCheckAtom,
20+
releaseCheckError,
21+
releaseCheckValue,
22+
} from "./environmentUpdateCheck";
1923

2024
export function OutdatedServerUpdateSection({
2125
environmentId,
@@ -27,37 +31,22 @@ export function OutdatedServerUpdateSection({
2731
const describe = useAtomCommand(describeOutdatedServer, { reportFailure: false });
2832
const update = useAtomCommand(updateOutdatedServer, { reportFailure: false });
2933
const state = useAtomValue(serverEnvironment.updateStateAtom(environmentId));
30-
const [release, setRelease] = useState<{
31-
fromVersion: string;
32-
targetVersion: string | null;
33-
} | null>(null);
34-
const [checking, setChecking] = useState(false);
35-
const [error, setError] = useState<string | null>(null);
36-
const controller = useRef<AbortController | null>(null);
37-
useEffect(() => () => controller.current?.abort(), []);
34+
const [checkResult, startCheck] = useAtom(environmentReleaseCheckAtom(environmentId));
35+
const release = releaseCheckValue(checkResult);
36+
const checking = checkResult.waiting;
37+
// Starting an update replaces a failed check's message with the update's own state.
38+
const [checkErrorDismissed, setCheckErrorDismissed] = useState(false);
39+
const error = checkErrorDismissed ? null : releaseCheckError(checkResult);
3840
const busy = checking || state.status === "running";
3941

40-
async function check() {
41-
if (busy || controller.current !== null) return;
42-
const request = new AbortController();
43-
controller.current = request;
44-
setChecking(true);
45-
setError(null);
46-
const timeout = setTimeout(() => request.abort(), 20_000);
47-
const result = await settlePromise(async () => {
42+
function check() {
43+
if (busy) return;
44+
setCheckErrorDismissed(false);
45+
startCheck(async () => {
4846
const description = await describe(environmentId);
4947
if (AsyncResult.isFailure(description)) throw squashAtomCommandFailure(description);
50-
const fromVersion = description.value.serverVersion;
51-
const targetVersion = await findEnvironmentUpdate(fromVersion, request.signal);
52-
if (!request.signal.aborted) setRelease({ fromVersion, targetVersion });
48+
return description.value.serverVersion;
5349
});
54-
clearTimeout(timeout);
55-
controller.current = null;
56-
setChecking(false);
57-
if (AsyncResult.isFailure(result)) {
58-
const failure = squashAtomCommandFailure(result);
59-
setError(failure instanceof Error ? failure.message : "Could not check for updates.");
60-
}
6150
}
6251

6352
function requestUpdate() {
@@ -71,7 +60,7 @@ export function OutdatedServerUpdateSection({
7160
{
7261
text: "Update",
7362
onPress: () => {
74-
setError(null);
63+
setCheckErrorDismissed(true);
7564
void update({
7665
environmentId,
7766
input: { targetVersion },
@@ -113,7 +102,7 @@ export function OutdatedServerUpdateSection({
113102
label="Check for updates"
114103
disabled={busy}
115104
loading={checking}
116-
onPress={() => void check()}
105+
onPress={check}
117106
/>
118107
{release?.targetVersion ? (
119108
<SettingsActionRow

‎apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx‎

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import * as Dialog from "../../components/ui/Dialog";
2-
import { useAtomValue } from "@effect/atom-react";
2+
import { useAtom, useAtomValue } from "@effect/atom-react";
33
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
44
import {
55
AuthProvidersManageScope,
@@ -8,8 +8,10 @@ import {
88
type ServerProvider,
99
} from "@t3tools/contracts";
1010
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
11+
import * as Cause from "effect/Cause";
12+
import * as Exit from "effect/Exit";
1113
import { AsyncResult } from "effect/reactivity";
12-
import { useEffect, useRef, useState } from "react";
14+
import { useRef, useState } from "react";
1315
import { View } from "react-native";
1416
import { useSafeAreaInsets } from "react-native-safe-area-context";
1517

@@ -31,9 +33,9 @@ import { SettingsSection } from "./components/SettingsSection";
3133
import {
3234
canMaintainEnvironment,
3335
canUpdateEnvironmentProvider,
34-
findEnvironmentUpdate,
3536
supportsEnvironmentUpdate,
3637
} from "./environment-maintenance";
38+
import { environmentReleaseCheckAtom, releaseCheckValue } from "./environmentUpdateCheck";
3739

3840
export function SettingsEnvironmentDetailRouteScreen({
3941
route,
@@ -70,12 +72,10 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
7072
const pendingRef = useRef(false);
7173
const [error, setError] = useState<string | null>(null);
7274
const [notice, setNotice] = useState<string | null>(null);
73-
const [release, setRelease] = useState<{
74-
fromVersion: string;
75-
targetVersion: string | null;
76-
} | null>(null);
77-
const checkController = useRef<AbortController | null>(null);
78-
useEffect(() => () => checkController.current?.abort(), []);
75+
const [releaseCheck, checkRelease] = useAtom(environmentReleaseCheckAtom(environmentId), {
76+
mode: "promiseExit",
77+
});
78+
const release = releaseCheckValue(releaseCheck);
7979

8080
const connected = environment?.isEnabled === true && environment.connectionState === "connected";
8181
const allowed =
@@ -145,7 +145,6 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
145145
},
146146
});
147147
if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
148-
setRelease(null);
149148
setNotice(`Updated to ${result.value.targetVersion}.`);
150149
}),
151150
},
@@ -267,19 +266,11 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
267266
loading={pending === "check"}
268267
onPress={() => {
269268
if (disabled) return;
269+
const fromVersion = config.environment.serverVersion;
270270
void run("check", async () => {
271-
const controller = new AbortController();
272-
checkController.current = controller;
273-
const timeout = setTimeout(() => controller.abort(), 20_000);
274-
const fromVersion = config.environment.serverVersion;
275-
const result = await settlePromise(() =>
276-
findEnvironmentUpdate(fromVersion, controller.signal),
277-
);
278-
clearTimeout(timeout);
279-
checkController.current = null;
271+
const exit = await checkRelease(async () => fromVersion);
280272
// `run` owns the error message, so a failed lookup rethrows to it.
281-
if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
282-
setRelease({ fromVersion, targetVersion: result.value });
273+
if (Exit.isFailure(exit)) throw Cause.squash(exit.cause);
283274
});
284275
}}
285276
/>

‎apps/mobile/src/features/settings/SettingsMicrophoneRouteScreen.tsx‎

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScroll
33
import { useAtomSet, useAtomValue } from "@effect/atom-react";
44
import { AsyncResult } from "effect/reactivity";
55
import { getRecordingPermissionsAsync, requestRecordingPermissionsAsync } from "expo-audio";
6-
import { useCallback, useEffect, useState } from "react";
7-
import { AppState, Linking, Pressable, View } from "react-native";
6+
import { useState } from "react";
7+
import { Linking, Pressable, View } from "react-native";
88
import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
99
import { useSafeAreaInsets } from "react-native-safe-area-context";
1010

1111
import { type AppSymbolName, SymbolView } from "../../components/ui/AppSymbol";
1212
import { AppText as Text } from "../../components/ui/AppText";
1313
import { cn } from "../../lib/cn";
14+
import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
1415
import {
1516
isMicrophoneDevice,
1617
type MicrophoneEntry,
@@ -28,28 +29,29 @@ const REMOVE_SIZE = 20;
2829

2930
type MicrophonePermission = "checking" | "granted" | "ask" | "denied";
3031

32+
function toMicrophonePermission(response: {
33+
readonly granted: boolean;
34+
readonly canAskAgain: boolean;
35+
}): MicrophonePermission {
36+
return response.granted ? "granted" : response.canAskAgain ? "ask" : "denied";
37+
}
38+
39+
const readMicrophonePermission = () =>
40+
getRecordingPermissionsAsync().then(toMicrophonePermission, (): MicrophonePermission => "ask");
41+
42+
const microphonePermissionAtom = makePermissionStatusAtom<MicrophonePermission>({
43+
label: "mobile:microphone-permission",
44+
initial: "checking",
45+
read: readMicrophonePermission,
46+
});
47+
3148
function useMicrophonePermission() {
32-
const [permission, setPermission] = useState<MicrophonePermission>("checking");
33-
const apply = useCallback(
34-
(response: { readonly granted: boolean; readonly canAskAgain: boolean }) =>
35-
setPermission(response.granted ? "granted" : response.canAskAgain ? "ask" : "denied"),
36-
[],
37-
);
38-
const refresh = useCallback(
39-
() => void getRecordingPermissionsAsync().then(apply, () => setPermission("ask")),
40-
[apply],
41-
);
42-
useEffect(() => {
43-
refresh();
44-
const subscription = AppState.addEventListener("change", (state) => {
45-
if (state === "active") refresh();
46-
});
47-
return () => subscription.remove();
48-
}, [refresh]);
49-
const request = useCallback(
50-
() => void requestRecordingPermissionsAsync().then(apply, refresh),
51-
[apply, refresh],
52-
);
49+
const permission = useAtomValue(microphonePermissionAtom);
50+
const setPermission = useAtomSet(microphonePermissionAtom);
51+
const request = () =>
52+
void requestRecordingPermissionsAsync()
53+
.then(toMicrophonePermission, readMicrophonePermission)
54+
.then(setPermission);
5355
return { permission, request };
5456
}
5557

‎apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx‎

Lines changed: 53 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import * as Notifications from "expo-notifications";
88
import { useNavigation } from "@react-navigation/native";
99
import * as Effect from "effect/Effect";
1010
import { AsyncResult } from "effect/reactivity";
11-
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
12-
import { AppState, Linking, Platform } from "react-native";
11+
import { useRef, useState, useSyncExternalStore } from "react";
12+
import { Linking, Platform } from "react-native";
1313
import { useSafeAreaInsets } from "react-native-safe-area-context";
1414

1515
import { AppText as Text } from "../../components/ui/AppText";
@@ -34,6 +34,7 @@ import {
3434
} from "../agent-awareness/remoteRegistration";
3535
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
3636
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
37+
import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
3738
import { runtime } from "../../lib/runtime";
3839
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
3940
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -46,6 +47,38 @@ import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen
4647
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
4748
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
4849

50+
const notificationStatusAtom = makePermissionStatusAtom<NotificationStatus>({
51+
label: "mobile:notification-permission",
52+
initial: "checking",
53+
read: async () => {
54+
if (Platform.OS !== "ios" && Platform.OS !== "android") return "unsupported";
55+
const result = await settlePromise(() => Notifications.getPermissionsAsync());
56+
if (result._tag === "Failure") {
57+
reportAtomCommandResult(result, { label: "notification permission refresh" });
58+
return "disabled";
59+
}
60+
return result.value.granted ? "enabled" : "disabled";
61+
},
62+
});
63+
64+
type LiveActivityBasis = {
65+
readonly isLoaded: boolean;
66+
readonly isSignedIn: boolean | undefined;
67+
readonly preferencesResult: unknown;
68+
};
69+
70+
function liveActivityStatusFrom(
71+
isLoaded: boolean,
72+
isSignedIn: boolean | undefined,
73+
preferencesResult: AsyncResult.AsyncResult<{ readonly liveActivitiesEnabled?: boolean }, unknown>,
74+
): LiveActivityStatus {
75+
if (!isLoaded) return "checking";
76+
if (!isSignedIn) return "signed-out";
77+
if (AsyncResult.isFailure(preferencesResult)) return "enabled";
78+
if (!AsyncResult.isSuccess(preferencesResult)) return "checking";
79+
return preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled";
80+
}
81+
4982
function useDeviceRegistered(): boolean {
5083
const status = useSyncExternalStore(
5184
subscribeAgentAwarenessRegistrationStatus,
@@ -87,8 +120,24 @@ function ConfiguredSettingsNotificationsRouteScreen() {
87120
const navigation = useNavigation();
88121
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
89122
const { savedConnectionsById } = useSavedRemoteConnections();
90-
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
91-
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
123+
const notificationStatus = useAtomValue(notificationStatusAtom);
124+
const setNotificationStatus = useAtomSet(notificationStatusAtom);
125+
// A write in progress or a failed one shows its own status until the auth or
126+
// preference state it was based on changes.
127+
const [liveActivityOverride, setLiveActivityOverride] = useState<{
128+
readonly status: LiveActivityStatus;
129+
readonly basis: LiveActivityBasis;
130+
} | null>(null);
131+
const liveActivityBasis: LiveActivityBasis = { isLoaded, isSignedIn, preferencesResult };
132+
const liveActivityStatus =
133+
liveActivityOverride !== null &&
134+
liveActivityOverride.basis.isLoaded === isLoaded &&
135+
liveActivityOverride.basis.isSignedIn === isSignedIn &&
136+
liveActivityOverride.basis.preferencesResult === preferencesResult
137+
? liveActivityOverride.status
138+
: liveActivityStatusFrom(isLoaded, isSignedIn, preferencesResult);
139+
const setLiveActivityStatus = (status: LiveActivityStatus) =>
140+
setLiveActivityOverride({ status, basis: liveActivityBasis });
92141
const liveActivityWriteInFlight = useRef(false);
93142
const deviceRegistered = useDeviceRegistered();
94143
const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
@@ -101,53 +150,6 @@ function ConfiguredSettingsNotificationsRouteScreen() {
101150
const connections = Object.values(savedConnectionsById);
102151
const environmentCount = connections.length;
103152

104-
const refreshNotifications = async () => {
105-
if (Platform.OS !== "ios" && Platform.OS !== "android") {
106-
setNotificationStatus("unsupported");
107-
return;
108-
}
109-
const result = await settlePromise(() => Notifications.getPermissionsAsync());
110-
if (result._tag === "Failure") {
111-
reportAtomCommandResult(result, { label: "notification permission refresh" });
112-
setNotificationStatus("disabled");
113-
return;
114-
}
115-
setNotificationStatus(result.value.granted ? "enabled" : "disabled");
116-
};
117-
118-
useEffect(() => {
119-
// oxlint-disable-next-line react/set-state-in-effect -- Reads native notification permission on mount and on every foreground.
120-
void refreshNotifications();
121-
const subscription = AppState.addEventListener("change", (state) => {
122-
if (state === "active") void refreshNotifications();
123-
});
124-
return () => subscription.remove();
125-
}, [refreshNotifications]);
126-
127-
useEffect(() => {
128-
if (!isLoaded) {
129-
// oxlint-disable-next-line react/set-state-in-effect -- Live Activity status shows checking until stored preferences load.
130-
setLiveActivityStatus("checking");
131-
return;
132-
}
133-
if (!isSignedIn) {
134-
setLiveActivityStatus("signed-out");
135-
return;
136-
}
137-
if (!AsyncResult.isSuccess(preferencesResult)) {
138-
if (AsyncResult.isFailure(preferencesResult)) {
139-
reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });
140-
setLiveActivityStatus("enabled");
141-
} else {
142-
setLiveActivityStatus("checking");
143-
}
144-
return;
145-
}
146-
setLiveActivityStatus(
147-
preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",
148-
);
149-
}, [isLoaded, isSignedIn, preferencesResult]);
150-
151153
const requestNotifications = async () => {
152154
const result = await settleAsyncResult(() =>
153155
runtime.runPromiseExit(

0 commit comments

Comments
 (0)