@devries-cameron20 / t3code Mirror · read-only / commits / 58c31f293d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 14:30 UTC

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 27, 2026 at 04:35 UTC 58c31f293d9ca52aded8dcfbceb4f63c704a1b72
8 files changed +339 -127
apps/mobile/src/features/settings/OutdatedServerUpdateSection.tsx
+21 -32
@@ -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";
3 import type { EnvironmentId } from "@t3tools/contracts";
4 import { AsyncResult } from "effect/reactivity";
5 -import { useEffect, useRef, useState } from "react";
5 +import { useState } from "react";
6 import { View } from "react-native";
7
8 import { AppText as Text } from "../../components/ui/AppText";
@@ -15,7 +15,11 @@ import {
15 import { useAtomCommand } from "../../state/use-atom-command";
16 import { SettingsActionRow } from "./components/SettingsActionRow";
17 import { SettingsSection } from "./components/SettingsSection";
18 -import { findEnvironmentUpdate } from "./environment-maintenance";
18 +import {
19 + environmentReleaseCheckAtom,
20 + releaseCheckError,
21 + releaseCheckValue,
22 +} from "./environmentUpdateCheck";
23
24 export function OutdatedServerUpdateSection({
25 environmentId,
@@ -27,37 +31,22 @@ export function OutdatedServerUpdateSection({
31 const describe = useAtomCommand(describeOutdatedServer, { reportFailure: false });
32 const update = useAtomCommand(updateOutdatedServer, { reportFailure: false });
33 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);
40 const busy = checking || state.status === "running";
41
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 () => {
46 const description = await describe(environmentId);
47 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;
49 });
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 - }
50 }
51
52 function requestUpdate() {
@@ -71,7 +60,7 @@ export function OutdatedServerUpdateSection({
60 {
61 text: "Update",
62 onPress: () => {
74 - setError(null);
63 + setCheckErrorDismissed(true);
64 void update({
65 environmentId,
66 input: { targetVersion },
@@ -113,7 +102,7 @@ export function OutdatedServerUpdateSection({
102 label="Check for updates"
103 disabled={busy}
104 loading={checking}
116 - onPress={() => void check()}
105 + onPress={check}
106 />
107 {release?.targetVersion ? (
108 <SettingsActionRow
apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
+12 -21
@@ -1,5 +1,5 @@
1 import * as Dialog from "../../components/ui/Dialog";
2 -import { useAtomValue } from "@effect/atom-react";
2 +import { useAtom, useAtomValue } from "@effect/atom-react";
3 import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
4 import {
5 AuthProvidersManageScope,
@@ -8,8 +8,10 @@ import {
8 type ServerProvider,
9 } from "@t3tools/contracts";
10 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
11 +import * as Cause from "effect/Cause";
12 +import * as Exit from "effect/Exit";
13 import { AsyncResult } from "effect/reactivity";
12 -import { useEffect, useRef, useState } from "react";
14 +import { useRef, useState } from "react";
15 import { View } from "react-native";
16 import { useSafeAreaInsets } from "react-native-safe-area-context";
17
@@ -31,9 +33,9 @@ import { SettingsSection } from "./components/SettingsSection";
33 import {
34 canMaintainEnvironment,
35 canUpdateEnvironmentProvider,
34 - findEnvironmentUpdate,
36 supportsEnvironmentUpdate,
37 } from "./environment-maintenance";
38 +import { environmentReleaseCheckAtom, releaseCheckValue } from "./environmentUpdateCheck";
39
40 export function SettingsEnvironmentDetailRouteScreen({
41 route,
@@ -70,12 +72,10 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
72 const pendingRef = useRef(false);
73 const [error, setError] = useState<string | null>(null);
74 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);
79
80 const connected = environment?.isEnabled === true && environment.connectionState === "connected";
81 const allowed =
@@ -145,7 +145,6 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
145 },
146 });
147 if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
148 - setRelease(null);
148 setNotice(`Updated to ${result.value.targetVersion}.`);
149 }),
150 },
@@ -267,19 +266,11 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
266 loading={pending === "check"}
267 onPress={() => {
268 if (disabled) return;
269 + const fromVersion = config.environment.serverVersion;
270 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);
272 // `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);
274 });
275 }}
276 />
apps/mobile/src/features/settings/SettingsMicrophoneRouteScreen.tsx
+25 -23
@@ -3,14 +3,15 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScroll
3 import { useAtomSet, useAtomValue } from "@effect/atom-react";
4 import { AsyncResult } from "effect/reactivity";
5 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";
8 import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
9 import { useSafeAreaInsets } from "react-native-safe-area-context";
10
11 import { type AppSymbolName, SymbolView } from "../../components/ui/AppSymbol";
12 import { AppText as Text } from "../../components/ui/AppText";
13 import { cn } from "../../lib/cn";
14 +import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
15 import {
16 isMicrophoneDevice,
17 type MicrophoneEntry,
@@ -28,28 +29,29 @@ const REMOVE_SIZE = 20;
29
30 type MicrophonePermission = "checking" | "granted" | "ask" | "denied";
31
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 +
48 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);
55 return { permission, request };
56 }
57
apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+53 -51
@@ -8,8 +8,8 @@ import * as Notifications from "expo-notifications";
8 import { useNavigation } from "@react-navigation/native";
9 import * as Effect from "effect/Effect";
10 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";
13 import { useSafeAreaInsets } from "react-native-safe-area-context";
14
15 import { AppText as Text } from "../../components/ui/AppText";
@@ -34,6 +34,7 @@ import {
34 } from "../agent-awareness/remoteRegistration";
35 import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
36 import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
37 +import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
38 import { runtime } from "../../lib/runtime";
39 import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
40 import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -46,6 +47,38 @@ import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen
47 type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
48 type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
49
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 +
82 function useDeviceRegistered(): boolean {
83 const status = useSyncExternalStore(
84 subscribeAgentAwarenessRegistrationStatus,
@@ -87,8 +120,24 @@ function ConfiguredSettingsNotificationsRouteScreen() {
120 const navigation = useNavigation();
121 const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
122 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 });
141 const liveActivityWriteInFlight = useRef(false);
142 const deviceRegistered = useDeviceRegistered();
143 const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
@@ -101,53 +150,6 @@ function ConfiguredSettingsNotificationsRouteScreen() {
150 const connections = Object.values(savedConnectionsById);
151 const environmentCount = connections.length;
152
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 -
153 const requestNotifications = async () => {
154 const result = await settleAsyncResult(() =>
155 runtime.runPromiseExit(
apps/mobile/src/features/settings/environmentUpdateCheck.test.ts new
+67
@@ -0,0 +1,67 @@
1 +import { EnvironmentId } from "@t3tools/contracts";
2 +import { AtomRegistry } from "effect/reactivity";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4 +
5 +import { environmentReleaseCheckAtom, releaseCheckError } from "./environmentUpdateCheck";
6 +
7 +function stubHangingFetch() {
8 + const { promise: called, resolve } = Promise.withResolvers<AbortSignal>();
9 + vi.stubGlobal("fetch", (_url: string, init: { signal: AbortSignal }) => {
10 + resolve(init.signal);
11 + return new Promise((_resolve, reject) => {
12 + init.signal.addEventListener("abort", () => reject(init.signal.reason));
13 + });
14 + });
15 + return { called, [Symbol.dispose]: () => vi.unstubAllGlobals() };
16 +}
17 +
18 +function makeRegistry() {
19 + const tasks: Array<() => void> = [];
20 + const registry = AtomRegistry.make({
21 + scheduleTask: (task) => {
22 + tasks.push(task);
23 + return () => undefined;
24 + },
25 + });
26 + const flush = () => {
27 + for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();
28 + };
29 + return { registry, flush };
30 +}
31 +
32 +describe("environmentReleaseCheckAtom", () => {
33 + it("aborts the release lookup when the screen stops reading it", async () => {
34 + using fetchStub = stubHangingFetch();
35 + const { registry, flush } = makeRegistry();
36 + const atom = environmentReleaseCheckAtom(EnvironmentId.make("env-unmount"));
37 + const unmount = registry.mount(atom);
38 +
39 + registry.set(atom, async () => "0.0.40");
40 + const signal = await fetchStub.called;
41 + expect(signal.aborted).toBe(false);
42 +
43 + unmount();
44 + flush();
45 + expect(signal.aborted).toBe(true);
46 + });
47 +
48 + it("reports a timeout in words after 20 seconds", async () => {
49 + using fetchStub = stubHangingFetch();
50 + using _timers = { [Symbol.dispose]: () => vi.useRealTimers() };
51 + vi.useFakeTimers();
52 + const { registry, flush } = makeRegistry();
53 + const atom = environmentReleaseCheckAtom(EnvironmentId.make("env-timeout"));
54 + const unmount = registry.mount(atom);
55 +
56 + registry.set(atom, async () => "0.0.40");
57 + const signal = await fetchStub.called;
58 +
59 + await vi.advanceTimersByTimeAsync(20_000);
60 + expect(signal.aborted).toBe(true);
61 + expect(releaseCheckError(registry.get(atom))).toBe(
62 + "Checking for updates timed out. Try again.",
63 + );
64 + unmount();
65 + flush();
66 + });
67 +});
apps/mobile/src/features/settings/environmentUpdateCheck.ts new
+51
@@ -0,0 +1,51 @@
1 +import type { EnvironmentId } from "@t3tools/contracts";
2 +import * as Effect from "effect/Effect";
3 +import * as Option from "effect/Option";
4 +import { AsyncResult, Atom } from "effect/reactivity";
5 +
6 +import { findEnvironmentUpdate } from "./environment-maintenance";
7 +
8 +export interface EnvironmentReleaseCheck {
9 + readonly fromVersion: string;
10 + readonly targetVersion: string | null;
11 +}
12 +
13 +const asError = (cause: unknown) =>
14 + cause instanceof Error ? cause : new Error("Could not check for updates.");
15 +
16 +/**
17 + * Looks up the newest T3 Code release for one environment. The atom is not
18 + * kept alive, so leaving the screen interrupts the lookup and aborts its fetch.
19 + * The argument reads the server version, which an outdated server only
20 + * reports through a separate description request.
21 + */
22 +export const environmentReleaseCheckAtom = Atom.family((environmentId: EnvironmentId) =>
23 + Atom.fn((readServerVersion: () => Promise<string>) =>
24 + Effect.gen(function* () {
25 + const fromVersion = yield* Effect.tryPromise({ try: readServerVersion, catch: asError });
26 + const targetVersion = yield* Effect.tryPromise({
27 + try: (signal) => findEnvironmentUpdate(fromVersion, signal),
28 + catch: asError,
29 + }).pipe(
30 + Effect.timeoutOrElse({
31 + duration: "20 seconds",
32 + orElse: () => Effect.fail(new Error("Checking for updates timed out. Try again.")),
33 + }),
34 + );
35 + return { fromVersion, targetVersion } satisfies EnvironmentReleaseCheck;
36 + }),
37 + ).pipe(Atom.withLabel(`mobile:environment-release-check:${environmentId}`)),
38 +);
39 +
40 +export function releaseCheckValue(
41 + result: AsyncResult.AsyncResult<EnvironmentReleaseCheck, Error>,
42 +): EnvironmentReleaseCheck | null {
43 + return Option.getOrNull(AsyncResult.value(result));
44 +}
45 +
46 +export function releaseCheckError(
47 + result: AsyncResult.AsyncResult<EnvironmentReleaseCheck, Error>,
48 +): string | null {
49 + if (!AsyncResult.isFailure(result) || result.waiting) return null;
50 + return Option.getOrNull(AsyncResult.error(result))?.message ?? null;
51 +}
apps/mobile/src/lib/permissionStatusAtom.test.ts new
+83
@@ -0,0 +1,83 @@
1 +import { AtomRegistry } from "effect/reactivity";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 +
4 +const native = vi.hoisted(() => ({
5 + listeners: new Set<(state: string) => void>(),
6 +}));
7 +
8 +vi.mock("react-native", () => ({
9 + AppState: {
10 + currentState: "active",
11 + addEventListener: (_event: string, listener: (state: string) => void) => {
12 + native.listeners.add(listener);
13 + return { remove: () => native.listeners.delete(listener) };
14 + },
15 + },
16 + AccessibilityInfo: { addEventListener: () => ({ remove: () => undefined }) },
17 +}));
18 +
19 +import { makePermissionStatusAtom } from "./permissionStatusAtom";
20 +
21 +function deferredReads() {
22 + const pending: Array<(status: string) => void> = [];
23 + return {
24 + read: () => new Promise<string>((resolve) => pending.push(resolve)),
25 + resolveNext: async (status: string) => {
26 + pending.shift()?.(status);
27 + await Promise.resolve();
28 + },
29 + get count() {
30 + return pending.length;
31 + },
32 + };
33 +}
34 +
35 +function makeRegistry() {
36 + const tasks: Array<() => void> = [];
37 + const registry = AtomRegistry.make({
38 + scheduleTask: (task) => {
39 + tasks.push(task);
40 + return () => undefined;
41 + },
42 + });
43 + const flush = () => {
44 + for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();
45 + };
46 + return { registry, flush };
47 +}
48 +
49 +describe("makePermissionStatusAtom", () => {
50 + it("reads on mount and again each time the app returns to the foreground", async () => {
51 + const reads = deferredReads();
52 + const atom = makePermissionStatusAtom({ label: "test", initial: "checking", read: reads.read });
53 + const { registry, flush } = makeRegistry();
54 + const unmount = registry.mount(atom);
55 +
56 + expect(registry.get(atom)).toBe("checking");
57 + await reads.resolveNext("ask");
58 + expect(registry.get(atom)).toBe("ask");
59 +
60 + for (const listener of native.listeners) listener("background");
61 + expect(reads.count).toBe(0);
62 + for (const listener of native.listeners) listener("active");
63 + await reads.resolveNext("granted");
64 + expect(registry.get(atom)).toBe("granted");
65 +
66 + unmount();
67 + flush();
68 + expect(native.listeners.size).toBe(0);
69 + });
70 +
71 + it("stores a request's outcome", () => {
72 + const reads = deferredReads();
73 + const atom = makePermissionStatusAtom({ label: "test", initial: "checking", read: reads.read });
74 + const { registry, flush } = makeRegistry();
75 + const unmount = registry.mount(atom);
76 +
77 + registry.set(atom, "denied");
78 + expect(registry.get(atom)).toBe("denied");
79 +
80 + unmount();
81 + flush();
82 + });
83 +});
apps/mobile/src/lib/permissionStatusAtom.ts new
+27
@@ -0,0 +1,27 @@
1 +import { Atom } from "effect/reactivity";
2 +
3 +import { subscribeAppActive } from "./appState";
4 +
5 +/**
6 + * A system permission as the app last saw it. Reads it when first mounted and
7 + * again each time the app returns to the foreground, where the user may have
8 + * changed it in system Settings. Writing stores the outcome of a request.
9 + */
10 +export function makePermissionStatusAtom<S>(options: {
11 + readonly label: string;
12 + readonly initial: S;
13 + readonly read: () => Promise<S>;
14 +}): Atom.Writable<S, S> {
15 + return Atom.writable(
16 + (get) => {
17 + // A read that settles after unmount is dropped: setSelf on a disposed lifetime is a no-op.
18 + const refresh = () => {
19 + void options.read().then((status) => get.setSelf(status));
20 + };
21 + refresh();
22 + get.addFinalizer(subscribeAppActive(refresh));
23 + return options.initial;
24 + },
25 + (ctx, status: S) => ctx.setSelf(status),
26 + ).pipe(Atom.withLabel(options.label));
27 +}