Skip to content
TypeScript

refactor(mobile): settings permission and update checks without sync effects (#25895)

Julius Marminge58c31f293d9c
diff --git a/apps/mobile/src/features/settings/OutdatedServerUpdateSection.tsx b/apps/mobile/src/features/settings/OutdatedServerUpdateSection.tsx
index f421e81bc20..ae8512fdb68 100644
--- a/apps/mobile/src/features/settings/OutdatedServerUpdateSection.tsx
+++ b/apps/mobile/src/features/settings/OutdatedServerUpdateSection.tsx
@@ -1,8 +1,8 @@
-import { useAtomValue } from "@effect/atom-react";
-import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import { useAtom, useAtomValue } from "@effect/atom-react";
+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
-import { useEffect, useRef, useState } from "react";
+import { useState } from "react";
import { View } from "react-native";
import { AppText as Text } from "../../components/ui/AppText";
@@ -15,7 +15,11 @@ import {
import { useAtomCommand } from "../../state/use-atom-command";
import { SettingsActionRow } from "./components/SettingsActionRow";
import { SettingsSection } from "./components/SettingsSection";
-import { findEnvironmentUpdate } from "./environment-maintenance";
+import {
+ environmentReleaseCheckAtom,
+ releaseCheckError,
+ releaseCheckValue,
+} from "./environmentUpdateCheck";
export function OutdatedServerUpdateSection({
environmentId,
@@ -27,37 +31,22 @@ export function OutdatedServerUpdateSection({
const describe = useAtomCommand(describeOutdatedServer, { reportFailure: false });
const update = useAtomCommand(updateOutdatedServer, { reportFailure: false });
const state = useAtomValue(serverEnvironment.updateStateAtom(environmentId));
- const [release, setRelease] = useState<{
- fromVersion: string;
- targetVersion: string | null;
- } | null>(null);
- const [checking, setChecking] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const controller = useRef<AbortController | null>(null);
- useEffect(() => () => controller.current?.abort(), []);
+ const [checkResult, startCheck] = useAtom(environmentReleaseCheckAtom(environmentId));
+ const release = releaseCheckValue(checkResult);
+ const checking = checkResult.waiting;
+ // Starting an update replaces a failed check's message with the update's own state.
+ const [checkErrorDismissed, setCheckErrorDismissed] = useState(false);
+ const error = checkErrorDismissed ? null : releaseCheckError(checkResult);
const busy = checking || state.status === "running";
- async function check() {
- if (busy || controller.current !== null) return;
- const request = new AbortController();
- controller.current = request;
- setChecking(true);
- setError(null);
- const timeout = setTimeout(() => request.abort(), 20_000);
- const result = await settlePromise(async () => {
+ function check() {
+ if (busy) return;
+ setCheckErrorDismissed(false);
+ startCheck(async () => {
const description = await describe(environmentId);
if (AsyncResult.isFailure(description)) throw squashAtomCommandFailure(description);
- const fromVersion = description.value.serverVersion;
- const targetVersion = await findEnvironmentUpdate(fromVersion, request.signal);
- if (!request.signal.aborted) setRelease({ fromVersion, targetVersion });
+ return description.value.serverVersion;
});
- clearTimeout(timeout);
- controller.current = null;
- setChecking(false);
- if (AsyncResult.isFailure(result)) {
- const failure = squashAtomCommandFailure(result);
- setError(failure instanceof Error ? failure.message : "Could not check for updates.");
- }
}
function requestUpdate() {
@@ -71,7 +60,7 @@ export function OutdatedServerUpdateSection({
{
text: "Update",
onPress: () => {
- setError(null);
+ setCheckErrorDismissed(true);
void update({
environmentId,
input: { targetVersion },
@@ -113,7 +102,7 @@ export function OutdatedServerUpdateSection({
label="Check for updates"
disabled={busy}
loading={checking}
- onPress={() => void check()}
+ onPress={check}
/>
{release?.targetVersion ? (
<SettingsActionRow
diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
index 95592a3b810..752038c65f4 100644
--- a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
@@ -1,5 +1,5 @@
import * as Dialog from "../../components/ui/Dialog";
-import { useAtomValue } from "@effect/atom-react";
+import { useAtom, useAtomValue } from "@effect/atom-react";
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
import {
AuthProvidersManageScope,
@@ -8,8 +8,10 @@ import {
type ServerProvider,
} from "@t3tools/contracts";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import * as Cause from "effect/Cause";
+import * as Exit from "effect/Exit";
import { AsyncResult } from "effect/reactivity";
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import { View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -31,9 +33,9 @@ import { SettingsSection } from "./components/SettingsSection";
import {
canMaintainEnvironment,
canUpdateEnvironmentProvider,
- findEnvironmentUpdate,
supportsEnvironmentUpdate,
} from "./environment-maintenance";
+import { environmentReleaseCheckAtom, releaseCheckValue } from "./environmentUpdateCheck";
export function SettingsEnvironmentDetailRouteScreen({
route,
@@ -70,12 +72,10 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
const pendingRef = useRef(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
- const [release, setRelease] = useState<{
- fromVersion: string;
- targetVersion: string | null;
- } | null>(null);
- const checkController = useRef<AbortController | null>(null);
- useEffect(() => () => checkController.current?.abort(), []);
+ const [releaseCheck, checkRelease] = useAtom(environmentReleaseCheckAtom(environmentId), {
+ mode: "promiseExit",
+ });
+ const release = releaseCheckValue(releaseCheck);
const connected = environment?.isEnabled === true && environment.connectionState === "connected";
const allowed =
@@ -145,7 +145,6 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
},
});
if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
- setRelease(null);
setNotice(`Updated to ${result.value.targetVersion}.`);
}),
},
@@ -267,19 +266,11 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
loading={pending === "check"}
onPress={() => {
if (disabled) return;
+ const fromVersion = config.environment.serverVersion;
void run("check", async () => {
- const controller = new AbortController();
- checkController.current = controller;
- const timeout = setTimeout(() => controller.abort(), 20_000);
- const fromVersion = config.environment.serverVersion;
- const result = await settlePromise(() =>
- findEnvironmentUpdate(fromVersion, controller.signal),
- );
- clearTimeout(timeout);
- checkController.current = null;
+ const exit = await checkRelease(async () => fromVersion);
// `run` owns the error message, so a failed lookup rethrows to it.
- if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
- setRelease({ fromVersion, targetVersion: result.value });
+ if (Exit.isFailure(exit)) throw Cause.squash(exit.cause);
});
}}
/>
diff --git a/apps/mobile/src/features/settings/SettingsMicrophoneRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsMicrophoneRouteScreen.tsx
index a3a3b4a251e..adcf71595b1 100644
--- a/apps/mobile/src/features/settings/SettingsMicrophoneRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsMicrophoneRouteScreen.tsx
@@ -3,14 +3,15 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScroll
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/reactivity";
import { getRecordingPermissionsAsync, requestRecordingPermissionsAsync } from "expo-audio";
-import { useCallback, useEffect, useState } from "react";
-import { AppState, Linking, Pressable, View } from "react-native";
+import { useState } from "react";
+import { Linking, Pressable, View } from "react-native";
import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { type AppSymbolName, SymbolView } from "../../components/ui/AppSymbol";
import { AppText as Text } from "../../components/ui/AppText";
import { cn } from "../../lib/cn";
+import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
import {
isMicrophoneDevice,
type MicrophoneEntry,
@@ -28,28 +29,29 @@ const REMOVE_SIZE = 20;
type MicrophonePermission = "checking" | "granted" | "ask" | "denied";
+function toMicrophonePermission(response: {
+ readonly granted: boolean;
+ readonly canAskAgain: boolean;
+}): MicrophonePermission {
+ return response.granted ? "granted" : response.canAskAgain ? "ask" : "denied";
+}
+
+const readMicrophonePermission = () =>
+ getRecordingPermissionsAsync().then(toMicrophonePermission, (): MicrophonePermission => "ask");
+
+const microphonePermissionAtom = makePermissionStatusAtom<MicrophonePermission>({
+ label: "mobile:microphone-permission",
+ initial: "checking",
+ read: readMicrophonePermission,
+});
+
function useMicrophonePermission() {
- const [permission, setPermission] = useState<MicrophonePermission>("checking");
- const apply = useCallback(
- (response: { readonly granted: boolean; readonly canAskAgain: boolean }) =>
- setPermission(response.granted ? "granted" : response.canAskAgain ? "ask" : "denied"),
- [],
- );
- const refresh = useCallback(
- () => void getRecordingPermissionsAsync().then(apply, () => setPermission("ask")),
- [apply],
- );
- useEffect(() => {
- refresh();
- const subscription = AppState.addEventListener("change", (state) => {
- if (state === "active") refresh();
- });
- return () => subscription.remove();
- }, [refresh]);
- const request = useCallback(
- () => void requestRecordingPermissionsAsync().then(apply, refresh),
- [apply, refresh],
- );
+ const permission = useAtomValue(microphonePermissionAtom);
+ const setPermission = useAtomSet(microphonePermissionAtom);
+ const request = () =>
+ void requestRecordingPermissionsAsync()
+ .then(toMicrophonePermission, readMicrophonePermission)
+ .then(setPermission);
return { permission, request };
}
diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
index 701403f3a4b..4aa5cc4c70b 100644
--- a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
@@ -8,8 +8,8 @@ import * as Notifications from "expo-notifications";
import { useNavigation } from "@react-navigation/native";
import * as Effect from "effect/Effect";
import { AsyncResult } from "effect/reactivity";
-import { useEffect, useRef, useState, useSyncExternalStore } from "react";
-import { AppState, Linking, Platform } from "react-native";
+import { useRef, useState, useSyncExternalStore } from "react";
+import { Linking, Platform } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/ui/AppText";
@@ -34,6 +34,7 @@ import {
} from "../agent-awareness/remoteRegistration";
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
+import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
import { runtime } from "../../lib/runtime";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -46,6 +47,38 @@ import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
+const notificationStatusAtom = makePermissionStatusAtom<NotificationStatus>({
+ label: "mobile:notification-permission",
+ initial: "checking",
+ read: async () => {
+ if (Platform.OS !== "ios" && Platform.OS !== "android") return "unsupported";
+ const result = await settlePromise(() => Notifications.getPermissionsAsync());
+ if (result._tag === "Failure") {
+ reportAtomCommandResult(result, { label: "notification permission refresh" });
+ return "disabled";
+ }
+ return result.value.granted ? "enabled" : "disabled";
+ },
+});
+
+type LiveActivityBasis = {
+ readonly isLoaded: boolean;
+ readonly isSignedIn: boolean | undefined;
+ readonly preferencesResult: unknown;
+};
+
+function liveActivityStatusFrom(
+ isLoaded: boolean,
+ isSignedIn: boolean | undefined,
+ preferencesResult: AsyncResult.AsyncResult<{ readonly liveActivitiesEnabled?: boolean }, unknown>,
+): LiveActivityStatus {
+ if (!isLoaded) return "checking";
+ if (!isSignedIn) return "signed-out";
+ if (AsyncResult.isFailure(preferencesResult)) return "enabled";
+ if (!AsyncResult.isSuccess(preferencesResult)) return "checking";
+ return preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled";
+}
+
function useDeviceRegistered(): boolean {
const status = useSyncExternalStore(
subscribeAgentAwarenessRegistrationStatus,
@@ -87,8 +120,24 @@ function ConfiguredSettingsNotificationsRouteScreen() {
const navigation = useNavigation();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { savedConnectionsById } = useSavedRemoteConnections();
- const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
- const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
+ const notificationStatus = useAtomValue(notificationStatusAtom);
+ const setNotificationStatus = useAtomSet(notificationStatusAtom);
+ // A write in progress or a failed one shows its own status until the auth or
+ // preference state it was based on changes.
+ const [liveActivityOverride, setLiveActivityOverride] = useState<{
+ readonly status: LiveActivityStatus;
+ readonly basis: LiveActivityBasis;
+ } | null>(null);
+ const liveActivityBasis: LiveActivityBasis = { isLoaded, isSignedIn, preferencesResult };
+ const liveActivityStatus =
+ liveActivityOverride !== null &&
+ liveActivityOverride.basis.isLoaded === isLoaded &&
+ liveActivityOverride.basis.isSignedIn === isSignedIn &&
+ liveActivityOverride.basis.preferencesResult === preferencesResult
+ ? liveActivityOverride.status
+ : liveActivityStatusFrom(isLoaded, isSignedIn, preferencesResult);
+ const setLiveActivityStatus = (status: LiveActivityStatus) =>
+ setLiveActivityOverride({ status, basis: liveActivityBasis });
const liveActivityWriteInFlight = useRef(false);
const deviceRegistered = useDeviceRegistered();
const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
@@ -101,53 +150,6 @@ function ConfiguredSettingsNotificationsRouteScreen() {
const connections = Object.values(savedConnectionsById);
const environmentCount = connections.length;
- const refreshNotifications = async () => {
- if (Platform.OS !== "ios" && Platform.OS !== "android") {
- setNotificationStatus("unsupported");
- return;
- }
- const result = await settlePromise(() => Notifications.getPermissionsAsync());
- if (result._tag === "Failure") {
- reportAtomCommandResult(result, { label: "notification permission refresh" });
- setNotificationStatus("disabled");
- return;
- }
- setNotificationStatus(result.value.granted ? "enabled" : "disabled");
- };
-
- useEffect(() => {
- // oxlint-disable-next-line react/set-state-in-effect -- Reads native notification permission on mount and on every foreground.
- void refreshNotifications();
- const subscription = AppState.addEventListener("change", (state) => {
- if (state === "active") void refreshNotifications();
- });
- return () => subscription.remove();
- }, [refreshNotifications]);
-
- useEffect(() => {
- if (!isLoaded) {
- // oxlint-disable-next-line react/set-state-in-effect -- Live Activity status shows checking until stored preferences load.
- setLiveActivityStatus("checking");
- return;
- }
- if (!isSignedIn) {
- setLiveActivityStatus("signed-out");
- return;
- }
- if (!AsyncResult.isSuccess(preferencesResult)) {
- if (AsyncResult.isFailure(preferencesResult)) {
- reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });
- setLiveActivityStatus("enabled");
- } else {
- setLiveActivityStatus("checking");
- }
- return;
- }
- setLiveActivityStatus(
- preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",
- );
- }, [isLoaded, isSignedIn, preferencesResult]);
-
const requestNotifications = async () => {
const result = await settleAsyncResult(() =>
runtime.runPromiseExit(
diff --git a/apps/mobile/src/features/settings/environmentUpdateCheck.test.ts b/apps/mobile/src/features/settings/environmentUpdateCheck.test.ts
new file mode 100644
index 00000000000..c1db446e664
--- /dev/null
+++ b/apps/mobile/src/features/settings/environmentUpdateCheck.test.ts
@@ -0,0 +1,67 @@
+import { EnvironmentId } from "@t3tools/contracts";
+import { AtomRegistry } from "effect/reactivity";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { environmentReleaseCheckAtom, releaseCheckError } from "./environmentUpdateCheck";
+
+function stubHangingFetch() {
+ const { promise: called, resolve } = Promise.withResolvers<AbortSignal>();
+ vi.stubGlobal("fetch", (_url: string, init: { signal: AbortSignal }) => {
+ resolve(init.signal);
+ return new Promise((_resolve, reject) => {
+ init.signal.addEventListener("abort", () => reject(init.signal.reason));
+ });
+ });
+ return { called, [Symbol.dispose]: () => vi.unstubAllGlobals() };
+}
+
+function makeRegistry() {
+ const tasks: Array<() => void> = [];
+ const registry = AtomRegistry.make({
+ scheduleTask: (task) => {
+ tasks.push(task);
+ return () => undefined;
+ },
+ });
+ const flush = () => {
+ for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();
+ };
+ return { registry, flush };
+}
+
+describe("environmentReleaseCheckAtom", () => {
+ it("aborts the release lookup when the screen stops reading it", async () => {
+ using fetchStub = stubHangingFetch();
+ const { registry, flush } = makeRegistry();
+ const atom = environmentReleaseCheckAtom(EnvironmentId.make("env-unmount"));
+ const unmount = registry.mount(atom);
+
+ registry.set(atom, async () => "0.0.40");
+ const signal = await fetchStub.called;
+ expect(signal.aborted).toBe(false);
+
+ unmount();
+ flush();
+ expect(signal.aborted).toBe(true);
+ });
+
+ it("reports a timeout in words after 20 seconds", async () => {
+ using fetchStub = stubHangingFetch();
+ using _timers = { [Symbol.dispose]: () => vi.useRealTimers() };
+ vi.useFakeTimers();
+ const { registry, flush } = makeRegistry();
+ const atom = environmentReleaseCheckAtom(EnvironmentId.make("env-timeout"));
+ const unmount = registry.mount(atom);
+
+ registry.set(atom, async () => "0.0.40");
+ const signal = await fetchStub.called;
+
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(signal.aborted).toBe(true);
+ expect(releaseCheckError(registry.get(atom))).toBe(
+ "Checking for updates timed out. Try again.",
+ );
+ unmount();
+ flush();
+ });
+});
diff --git a/apps/mobile/src/features/settings/environmentUpdateCheck.ts b/apps/mobile/src/features/settings/environmentUpdateCheck.ts
new file mode 100644
index 00000000000..b75bc06a394
--- /dev/null
+++ b/apps/mobile/src/features/settings/environmentUpdateCheck.ts
@@ -0,0 +1,51 @@
+import type { EnvironmentId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import { AsyncResult, Atom } from "effect/reactivity";
+
+import { findEnvironmentUpdate } from "./environment-maintenance";
+
+export interface EnvironmentReleaseCheck {
+ readonly fromVersion: string;
+ readonly targetVersion: string | null;
+}
+
+const asError = (cause: unknown) =>
+ cause instanceof Error ? cause : new Error("Could not check for updates.");
+
+/**
+ * Looks up the newest T3 Code release for one environment. The atom is not
+ * kept alive, so leaving the screen interrupts the lookup and aborts its fetch.
+ * The argument reads the server version, which an outdated server only
+ * reports through a separate description request.
+ */
+export const environmentReleaseCheckAtom = Atom.family((environmentId: EnvironmentId) =>
+ Atom.fn((readServerVersion: () => Promise<string>) =>
+ Effect.gen(function* () {
+ const fromVersion = yield* Effect.tryPromise({ try: readServerVersion, catch: asError });
+ const targetVersion = yield* Effect.tryPromise({
+ try: (signal) => findEnvironmentUpdate(fromVersion, signal),
+ catch: asError,
+ }).pipe(
+ Effect.timeoutOrElse({
+ duration: "20 seconds",
+ orElse: () => Effect.fail(new Error("Checking for updates timed out. Try again.")),
+ }),
+ );
+ return { fromVersion, targetVersion } satisfies EnvironmentReleaseCheck;
+ }),
+ ).pipe(Atom.withLabel(`mobile:environment-release-check:${environmentId}`)),
+);
+
+export function releaseCheckValue(
+ result: AsyncResult.AsyncResult<EnvironmentReleaseCheck, Error>,
+): EnvironmentReleaseCheck | null {
+ return Option.getOrNull(AsyncResult.value(result));
+}
+
+export function releaseCheckError(
+ result: AsyncResult.AsyncResult<EnvironmentReleaseCheck, Error>,
+): string | null {
+ if (!AsyncResult.isFailure(result) || result.waiting) return null;
+ return Option.getOrNull(AsyncResult.error(result))?.message ?? null;
+}
diff --git a/apps/mobile/src/lib/permissionStatusAtom.test.ts b/apps/mobile/src/lib/permissionStatusAtom.test.ts
new file mode 100644
index 00000000000..052b2a37cb0
--- /dev/null
+++ b/apps/mobile/src/lib/permissionStatusAtom.test.ts
@@ -0,0 +1,83 @@
+import { AtomRegistry } from "effect/reactivity";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+const native = vi.hoisted(() => ({
+ listeners: new Set<(state: string) => void>(),
+}));
+
+vi.mock("react-native", () => ({
+ AppState: {
+ currentState: "active",
+ addEventListener: (_event: string, listener: (state: string) => void) => {
+ native.listeners.add(listener);
+ return { remove: () => native.listeners.delete(listener) };
+ },
+ },
+ AccessibilityInfo: { addEventListener: () => ({ remove: () => undefined }) },
+}));
+
+import { makePermissionStatusAtom } from "./permissionStatusAtom";
+
+function deferredReads() {
+ const pending: Array<(status: string) => void> = [];
+ return {
+ read: () => new Promise<string>((resolve) => pending.push(resolve)),
+ resolveNext: async (status: string) => {
+ pending.shift()?.(status);
+ await Promise.resolve();
+ },
+ get count() {
+ return pending.length;
+ },
+ };
+}
+
+function makeRegistry() {
+ const tasks: Array<() => void> = [];
+ const registry = AtomRegistry.make({
+ scheduleTask: (task) => {
+ tasks.push(task);
+ return () => undefined;
+ },
+ });
+ const flush = () => {
+ for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();
+ };
+ return { registry, flush };
+}
+
+describe("makePermissionStatusAtom", () => {
+ it("reads on mount and again each time the app returns to the foreground", async () => {
+ const reads = deferredReads();
+ const atom = makePermissionStatusAtom({ label: "test", initial: "checking", read: reads.read });
+ const { registry, flush } = makeRegistry();
+ const unmount = registry.mount(atom);
+
+ expect(registry.get(atom)).toBe("checking");
+ await reads.resolveNext("ask");
+ expect(registry.get(atom)).toBe("ask");
+
+ for (const listener of native.listeners) listener("background");
+ expect(reads.count).toBe(0);
+ for (const listener of native.listeners) listener("active");
+ await reads.resolveNext("granted");
+ expect(registry.get(atom)).toBe("granted");
+
+ unmount();
+ flush();
+ expect(native.listeners.size).toBe(0);
+ });
+
+ it("stores a request's outcome", () => {
+ const reads = deferredReads();
+ const atom = makePermissionStatusAtom({ label: "test", initial: "checking", read: reads.read });
+ const { registry, flush } = makeRegistry();
+ const unmount = registry.mount(atom);
+
+ registry.set(atom, "denied");
+ expect(registry.get(atom)).toBe("denied");
+
+ unmount();
+ flush();
+ });
+});
diff --git a/apps/mobile/src/lib/permissionStatusAtom.ts b/apps/mobile/src/lib/permissionStatusAtom.ts
new file mode 100644
index 00000000000..ee8ff5dcdfe
--- /dev/null
+++ b/apps/mobile/src/lib/permissionStatusAtom.ts
@@ -0,0 +1,27 @@
+import { Atom } from "effect/reactivity";
+
+import { subscribeAppActive } from "./appState";
+
+/**
+ * A system permission as the app last saw it. Reads it when first mounted and
+ * again each time the app returns to the foreground, where the user may have
+ * changed it in system Settings. Writing stores the outcome of a request.
+ */
+export function makePermissionStatusAtom<S>(options: {
+ readonly label: string;
+ readonly initial: S;
+ readonly read: () => Promise<S>;
+}): Atom.Writable<S, S> {
+ return Atom.writable(
+ (get) => {
+ // A read that settles after unmount is dropped: setSelf on a disposed lifetime is a no-op.
+ const refresh = () => {
+ void options.read().then((status) => get.setSelf(status));
+ };
+ refresh();
+ get.addFinalizer(subscribeAppActive(refresh));
+ return options.initial;
+ },
+ (ctx, status: S) => ctx.setSelf(status),
+ ).pipe(Atom.withLabel(options.label));
+}