Skip to content

Commit 31be8be

Browse files
fix(mobile): keep scoped settings writes and notifications consistent
1 parent 851e6ca commit 31be8be

8 files changed

Lines changed: 98 additions & 48 deletions

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

Lines changed: 58 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import * as Notifications from "expo-notifications";
55
import { useNavigation } from "@react-navigation/native";
66
import * as Effect from "effect/Effect";
77
import { AsyncResult } from "effect/unstable/reactivity";
8-
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
9-
import { Alert, Linking, Platform } from "react-native";
8+
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
9+
import { Alert, AppState, Linking, Platform } from "react-native";
1010
import { useSafeAreaInsets } from "react-native-safe-area-context";
1111

1212
import { AppText as Text } from "../../components/AppText";
@@ -90,10 +90,14 @@ function ConfiguredSettingsNotificationsRouteScreen() {
9090
const { savedConnectionsById } = useSavedRemoteConnections();
9191
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
9292
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
93+
const liveActivityWriteInFlight = useRef(false);
9394
const deviceRegistered = useDeviceRegistered();
9495
const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
9596
? preferencesResult.value.liveActivitiesEnabled !== false
9697
: true;
98+
const canClearLiveActivitiesPreference =
99+
AsyncResult.isSuccess(preferencesResult) &&
100+
preferencesResult.value.liveActivitiesEnabled !== false;
97101

98102
const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
99103
const environmentCount = connections.length;
@@ -114,6 +118,10 @@ function ConfiguredSettingsNotificationsRouteScreen() {
114118

115119
useEffect(() => {
116120
void refreshNotifications();
121+
const subscription = AppState.addEventListener("change", (state) => {
122+
if (state === "active") void refreshNotifications();
123+
});
124+
return () => subscription.remove();
117125
}, [refreshNotifications]);
118126

119127
useEffect(() => {
@@ -338,42 +346,50 @@ function ConfiguredSettingsNotificationsRouteScreen() {
338346

339347
const handleLiveActivitiesChange = useCallback(
340348
(enabled: boolean) => {
349+
if (liveActivityWriteInFlight.current) return;
341350
if (!enabled) {
342-
setLiveActivityStatus("disabled");
351+
liveActivityWriteInFlight.current = true;
352+
setLiveActivityStatus("linking");
343353
void (async () => {
344-
let token: string | null = null;
345-
if (isSignedIn) {
346-
const tokenResult = await settlePromise(() =>
347-
getToken(resolveRelayClerkTokenOptions()),
354+
try {
355+
let token: string | null = null;
356+
if (isSignedIn) {
357+
const tokenResult = await settlePromise(() =>
358+
getToken(resolveRelayClerkTokenOptions()),
359+
);
360+
if (tokenResult._tag === "Failure") {
361+
setLiveActivityStatus("enabled");
362+
reportAtomCommandResult(tokenResult, {
363+
label: "live activity disable token lookup",
364+
});
365+
return;
366+
}
367+
token = tokenResult.value;
368+
}
369+
370+
const updateResult = await settleAsyncResult(() =>
371+
runtime.runPromiseExit(
372+
setLiveActivityUpdatesEnabled({
373+
enabled: false,
374+
previousEnabled: liveActivitiesPreferenceEnabled,
375+
clerkToken: token,
376+
connections,
377+
}),
378+
),
348379
);
349-
if (tokenResult._tag === "Failure") {
350-
reportAtomCommandResult(tokenResult, {
351-
label: "live activity disable token lookup",
380+
if (updateResult._tag === "Failure") {
381+
setLiveActivityStatus(isSignedIn ? "enabled" : "signed-out");
382+
reportAtomCommandResult(updateResult, {
383+
label: "live activity disable",
352384
});
353385
return;
354386
}
355-
token = tokenResult.value;
356-
}
357-
358-
const updateResult = await settleAsyncResult(() =>
359-
runtime.runPromiseExit(
360-
setLiveActivityUpdatesEnabled({
361-
enabled: false,
362-
previousEnabled: liveActivitiesPreferenceEnabled,
363-
clerkToken: token,
364-
connections,
365-
}),
366-
),
367-
);
368-
if (updateResult._tag === "Failure") {
369-
setLiveActivityStatus("enabled");
370-
reportAtomCommandResult(updateResult, {
371-
label: "live activity disable",
372-
});
373-
return;
387+
savePreferences({ liveActivitiesEnabled: false });
388+
refreshManagedRelayEnvironments();
389+
setLiveActivityStatus("disabled");
390+
} finally {
391+
liveActivityWriteInFlight.current = false;
374392
}
375-
savePreferences({ liveActivitiesEnabled: false });
376-
refreshManagedRelayEnvironments();
377393
})();
378394
return;
379395
}
@@ -383,7 +399,10 @@ function ConfiguredSettingsNotificationsRouteScreen() {
383399
return;
384400
}
385401

386-
void linkEnvironments();
402+
liveActivityWriteInFlight.current = true;
403+
void linkEnvironments().finally(() => {
404+
liveActivityWriteInFlight.current = false;
405+
});
387406
},
388407
[
389408
connections,
@@ -452,6 +471,13 @@ function ConfiguredSettingsNotificationsRouteScreen() {
452471
}
453472
onValueChange={handleLiveActivitiesChange}
454473
/>
474+
{liveActivityStatus === "signed-out" && canClearLiveActivitiesPreference ? (
475+
<SettingsRow
476+
icon="bolt.circle"
477+
label="Turn off Live Activity preference"
478+
onPress={() => handleLiveActivitiesChange(false)}
479+
/>
480+
) : null}
455481
{supportsAndroidLiveUpdateSettings() ? (
456482
<SettingsRow
457483
icon="bolt.circle"

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

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -76,14 +76,15 @@ function ProjectOverviewContent(props: {
7676
setIsSaving(true);
7777
void (async () => {
7878
try {
79-
for (const member of props.members) {
80-
const result = await updateProject({
81-
environmentId: member.environmentId,
82-
input: { projectId: member.id, title: nextName },
83-
});
84-
if (result._tag === "Failure") return;
85-
}
86-
setDraftName(null);
79+
const results = await Promise.all(
80+
props.members.map((member) =>
81+
updateProject({
82+
environmentId: member.environmentId,
83+
input: { projectId: member.id, title: nextName },
84+
}),
85+
),
86+
);
87+
if (results.every((result) => result._tag !== "Failure")) setDraftName(null);
8788
} finally {
8889
setIsSaving(false);
8990
}

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
PROJECT_SCOPED_SERVER_SETTING_KEYS,
1010
type ProjectScopedServerSettingKey,
1111
} from "@t3tools/contracts";
12-
import { useState, type ComponentProps } from "react";
12+
import { useRef, useState, type ComponentProps } from "react";
1313
import { Alert, Platform, Pressable, View } from "react-native";
1414
import { useSafeAreaInsets } from "react-native-safe-area-context";
1515

@@ -113,6 +113,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
113113
projectSelected ? (selectedProject?.members.map((member) => member.project) ?? []) : null,
114114
);
115115
const [pendingWrites, setPendingWrites] = useState(0);
116+
const writeInFlight = useRef(false);
116117
const [pendingTargets, setPendingTargets] = useState<
117118
readonly ScopedMobileSettingsTarget[] | null
118119
>(null);
@@ -129,30 +130,35 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
129130
reportFailure: true,
130131
});
131132
const write = (patch: ServerSettingsPatch) => {
132-
if (!hasConnectedSelection) return;
133+
if (writeInFlight.current || !hasConnectedSelection) return;
133134
const writes = planMobileScopedSettingsPatch(targets, projectSelected, patch);
134135
if (writes.length === 0) return;
136+
writeInFlight.current = true;
135137
setPendingTargets(targets);
136138
setPendingWrites((count) => count + 1);
137139
void Promise.allSettled(
138140
writes.map((entry) =>
139141
updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),
140142
),
141143
).finally(() => {
144+
writeInFlight.current = false;
142145
setPendingTargets(null);
143146
setPendingWrites((count) => count - 1);
144147
});
145148
};
146149
const clearProjectOverrides = () => {
150+
if (writeInFlight.current) return;
147151
const writes = planMobileScopedSettingsClear(targets, PAGE_PROJECT_KEYS[props.page]);
148152
if (writes.length === 0) return;
153+
writeInFlight.current = true;
149154
setPendingTargets(targets);
150155
setPendingWrites((count) => count + 1);
151156
void Promise.allSettled(
152157
writes.map((entry) =>
153158
updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),
154159
),
155160
).finally(() => {
161+
writeInFlight.current = false;
156162
setPendingTargets(null);
157163
setPendingWrites((count) => count - 1);
158164
});

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { AutoSettleDaysField } from "./components/AutoSettleDaysField";
22
import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
33
import { useAtomSet, useAtomValue } from "@effect/atom-react";
44
import { AsyncResult } from "effect/unstable/reactivity";
5-
import { useState } from "react";
5+
import { useRef, useState } from "react";
66
import { Platform, Pressable, View } from "react-native";
77
import { useSafeAreaInsets } from "react-native-safe-area-context";
88

@@ -63,6 +63,7 @@ function AutoSettleSettingsRows() {
6363
const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);
6464
const projectSelected = selectedProjectKey !== null;
6565
const [pendingWrites, setPendingWrites] = useState(0);
66+
const writeInFlight = useRef(false);
6667
const [pendingTargets, setPendingTargets] = useState<
6768
readonly ScopedMobileSettingsTarget[] | null
6869
>(null);
@@ -86,16 +87,18 @@ function AutoSettleSettingsRows() {
8687
}
8788

8889
const writeToAll = (patch: Partial<AutoSettleSettings>) => {
89-
if (pendingWrites > 0) return;
90+
if (writeInFlight.current) return;
9091
const writes = planMobileScopedSettingsPatch(syncTargets, projectSelected, patch);
9192
if (writes.length === 0) return;
93+
writeInFlight.current = true;
9294
setPendingTargets(syncTargets);
9395
setPendingWrites((count) => count + 1);
9496
void Promise.allSettled(
9597
writes.map((entry) =>
9698
updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),
9799
),
98100
).finally(() => {
101+
writeInFlight.current = false;
99102
setPendingTargets(null);
100103
setPendingWrites((count) => count - 1);
101104
});
@@ -128,18 +131,21 @@ function AutoSettleSettingsRows() {
128131
target.sources.sidebarAutoSettleAfterDays === "project",
129132
);
130133
const clearProjectOverrides = () => {
134+
if (writeInFlight.current) return;
131135
const writes = planMobileScopedSettingsClear(syncTargets, [
132136
"sidebarAutoSettleOnMerge",
133137
"sidebarAutoSettleAfterDays",
134138
]);
135139
if (writes.length === 0) return;
140+
writeInFlight.current = true;
136141
setPendingTargets(syncTargets);
137142
setPendingWrites((count) => count + 1);
138143
void Promise.allSettled(
139144
writes.map((entry) =>
140145
updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),
141146
),
142147
).finally(() => {
148+
writeInFlight.current = false;
143149
setPendingTargets(null);
144150
setPendingWrites((count) => count - 1);
145151
});

‎apps/mobile/src/features/settings/components/AutoSettleDaysField.android.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import type { AutoSettleDaysFieldProps } from "./AutoSettleDaysField";
1010

1111
export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {
1212
const adjust = (amount: number) => {
13+
if (props.disabled) return;
1314
const next = Math.max(
1415
MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
1516
Math.min(MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, props.value + amount),
@@ -28,7 +29,7 @@ export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {
2829
<MaterialIconButton
2930
icon="minus"
3031
accessibilityLabel="Decrease days before auto-settle"
31-
disabled={props.value <= MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}
32+
disabled={props.disabled || props.value <= MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}
3233
onPress={() => adjust(-1)}
3334
/>
3435
<AppText
@@ -42,7 +43,7 @@ export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {
4243
<MaterialIconButton
4344
icon="plus"
4445
accessibilityLabel="Increase days before auto-settle"
45-
disabled={props.value >= MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}
46+
disabled={props.disabled || props.value >= MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}
4647
onPress={() => adjust(1)}
4748
/>
4849
</View>

‎apps/mobile/src/features/settings/components/AutoSettleDaysField.ios.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Button, Host, HStack, Picker, Popover, Text, VStack } from "@expo/ui/sw
22
import {
33
accessibilityLabel,
44
buttonStyle,
5+
disabled,
56
font,
67
foregroundStyle,
78
frame,
@@ -34,11 +35,13 @@ export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {
3435
<Popover.Trigger>
3536
<Button
3637
onPress={() => {
38+
if (props.disabled) return;
3739
setDraft(props.value);
3840
setOpen(true);
3941
}}
4042
modifiers={[
4143
buttonStyle("bordered"),
44+
disabled(props.disabled),
4245
accessibilityLabel(`Days before auto-settle: ${props.value}`),
4346
frame({ minWidth: 64, minHeight: 44 }),
4447
foregroundStyle(colors["--color-primary"]),
@@ -81,7 +84,7 @@ export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {
8184
label="Done"
8285
onPress={() => {
8386
setOpen(false);
84-
if (draft !== props.value) props.onValueChange(draft);
87+
if (!props.disabled && draft !== props.value) props.onValueChange(draft);
8588
}}
8689
modifiers={[foregroundStyle(colors["--color-primary"])]}
8790
/>

‎apps/mobile/src/features/settings/components/AutoSettleDaysField.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ export interface AutoSettleDaysFieldProps {
1515
export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {
1616
const [draft, setDraft] = useState<string | null>(null);
1717
const commit = () => {
18+
if (props.disabled) {
19+
setDraft(null);
20+
return;
21+
}
1822
const text = (draft ?? "").trim();
1923
setDraft(null);
2024
// Validate the whole input; decimals and trailing text must not become whole days.

‎apps/mobile/src/features/settings/components/SettingsEnvironmentFilterHeader.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export function SettingsEnvironmentFilterHeader(props: { readonly closeSettings?
1111
const navigation = useNavigation();
1212
const {
1313
availableTargets,
14+
selectedTargets,
1415
selectedIds,
1516
selectAll,
1617
toggleEnvironment,
@@ -47,7 +48,9 @@ export function SettingsEnvironmentFilterHeader(props: { readonly closeSettings?
4748
{
4849
type: "submenu",
4950
label:
50-
selectedIds === null ? "All environments" : `${selectedIds.size} environments`,
51+
selectedIds === null
52+
? "All environments"
53+
: `${selectedTargets.length} environments`,
5154
items: [
5255
{
5356
type: "action",

0 commit comments

Comments
 (0)