Skip to content

Commit b3add55

Browse files
refactor(mobile): settings and usage screens drop sync effects
Several mobile settings, connection, and usage screens synchronized state through effects: timers resetting labels, refs mirrored from props, header options set from layout effects, fetches into local state, and screens that bounced themselves closed when T3 Connect was not configured. - Connect onboarding and T3 Account deep links are dropped by the link filter when cloud config is missing, instead of mounting an empty screen that navigates back from an effect. - The permission-update notice is an app-start service subscribed to an atom, not a null component with two effects. - Diagnostics reads the crash log through an atom; About derives the "up to date" fade from a deadline; project removal reads the live filter selection through a getter instead of a mirrored ref. - The scheduled-task editor is cleared by the link handler for settings/scheduled-tasks/new, and saving closes the editor from the save handler. - The legal document header button is set with NativeStackScreenOptions. - Usage limits failures and auto refresh live in atoms; the updating dim is a Reanimated CSS transition. Effects: 15 -> 3 in touched files. Kept: App's splash/reconciliation effects (unchanged) and SettingsAuth's sign-out follower, which tracks Clerk's auth store. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3de45c6 commit b3add55

21 files changed

Lines changed: 569 additions & 391 deletions

‎apps/mobile/src/App.tsx‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { PermissionUpdateNotice } from "./features/connection/PermissionUpdateNotice";
1+
import { installPermissionUpdateNotice } from "./features/connection/permissionUpdateNotice";
22
import * as Linking from "expo-linking";
33
import * as SplashScreen from "expo-splash-screen";
44
import { useEffect } from "react";
@@ -31,6 +31,12 @@ import { environmentThreadShells } from "./state/threads";
3131
import { environmentShell } from "./state/shell";
3232
import { OverlayPortalHost } from "./components/ui/OverlayPortal";
3333
import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
34+
import { hasCloudPublicConfig } from "./features/cloud/publicConfig";
35+
import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state";
36+
import {
37+
disposeOnFoundationReplace,
38+
type FoundationHotModule,
39+
} from "./lib/foundation-fast-refresh";
3440
import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";
3541
import { useUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc";
3642
import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator";
@@ -58,7 +64,7 @@ void hydrateWorkspaceSelections();
5864
const appLinking = {
5965
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
6066
config: { initialRouteName: "Home" },
61-
filter: shouldHandleAppLink,
67+
filter: (url: string) => shouldHandleAppLink(url, hasCloudPublicConfig()),
6268
getInitialURL: async () => (await Linking.getInitialURL()) ?? (await launchWorkspaceURL()),
6369
getActionFromState: (
6470
state: Parameters<typeof getActionFromState>[0],
@@ -68,15 +74,25 @@ const appLinking = {
6874
(workspaceDetailLinkAction(state) as ReturnType<typeof getActionFromState>) ??
6975
getActionFromState(state, options),
7076
getStateFromPath: (path: string, options: Parameters<typeof getStateFromPath>[1]) =>
71-
restoreSettingsLinkState(
72-
restoreDraftLinkState(getStateFromPath(path, options), path),
73-
settingsLinkPage(),
77+
takeScheduledTaskNewLink(
78+
restoreSettingsLinkState(
79+
restoreDraftLinkState(getStateFromPath(path, options), path),
80+
settingsLinkPage(),
81+
),
7482
),
7583
};
7684

7785
const Navigation = createStaticNavigation(RootStack);
7886
const navigationRef = createNavigationContainerRef();
7987

88+
declare const module: { readonly hot?: FoundationHotModule } | undefined;
89+
90+
const disposePermissionUpdateNotice = installPermissionUpdateNotice();
91+
disposeOnFoundationReplace(
92+
typeof module === "undefined" ? undefined : module.hot,
93+
disposePermissionUpdateNotice,
94+
);
95+
8096
function SplashScreenCoordinator() {
8197
const { isReady } = useAppearancePreferences();
8298

@@ -119,7 +135,6 @@ function AppContent() {
119135
<>
120136
<SplashScreenCoordinator />
121137
<SubscriptionUsageCoordinator />
122-
<PermissionUpdateNotice />
123138
<GestureHandlerRootView className="flex-1">
124139
<KeyboardProvider statusBarTranslucent>
125140
<SafeAreaProvider>

‎apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx‎

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import { Button } from "../../components/ui/Button";
55
import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
66

77
import { useAuth } from "@clerk/expo";
8-
import { StackActions, useNavigation } from "@react-navigation/native";
9-
import { useEffect, useState } from "react";
8+
import { useNavigation } from "@react-navigation/native";
9+
import { useState } from "react";
1010
import { Platform, RefreshControl, View } from "react-native";
1111
import { useSafeAreaInsets } from "react-native-safe-area-context";
1212

@@ -19,21 +19,9 @@ import { useConnectionController } from "../connection/useConnectionController";
1919
import { optOutOfConnectOnboarding } from "./connectOnboardingOptOut";
2020
import { hasCloudPublicConfig } from "./publicConfig";
2121

22+
// Only reachable with cloud config: onboarding is requested after a T3 Connect
23+
// sign-in, and appLinking drops the deep link otherwise.
2224
export function ConnectOnboardingRouteScreen() {
23-
const navigation = useNavigation();
24-
25-
// Without cloud config, deep links must exit to avoid an empty, undismissable sheet.
26-
useEffect(() => {
27-
if (hasCloudPublicConfig()) {
28-
return;
29-
}
30-
if (navigation.canGoBack()) {
31-
navigation.goBack();
32-
} else {
33-
navigation.dispatch(StackActions.replace("Home"));
34-
}
35-
}, [navigation]);
36-
3725
return hasCloudPublicConfig() ? <ConfiguredConnectOnboardingRouteScreen /> : null;
3826
}
3927

‎apps/mobile/src/features/connection/PermissionUpdateNotice.tsx‎

Lines changed: 0 additions & 83 deletions
This file was deleted.
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import * as Dialog from "../../components/ui/Dialog";
2+
import { sessionHasLegacyPermissions } from "@t3tools/contracts";
3+
import { Atom } from "effect/reactivity";
4+
import * as SecureStore from "expo-secure-store";
5+
6+
import { whenProtectedDataAvailable } from "../../lib/protectedData";
7+
import { appAtomRegistry } from "../../state/atom-registry";
8+
import { projectEnvironmentPresentation } from "../../state/environments";
9+
import { environmentPresentations } from "../../state/presentation";
10+
import { environmentSession } from "../../state/session";
11+
12+
const storageKey = "t3code.permission-update.v1";
13+
14+
const legacyPermissionEnvironmentsAtom = Atom.make((get) =>
15+
[...get(environmentPresentations.presentationsAtom).entries()].flatMap(
16+
([environmentId, presentation]) => {
17+
const session = get(environmentSession.sessionStateAtom(environmentId));
18+
return session._tag === "Success" &&
19+
!session.waiting &&
20+
sessionHasLegacyPermissions(session.value)
21+
? [projectEnvironmentPresentation(environmentId, presentation)]
22+
: [];
23+
},
24+
),
25+
).pipe(Atom.withLabel("mobile:legacy-permission-environments"));
26+
27+
async function loadDismissedEnvironmentIds(): Promise<Set<string>> {
28+
try {
29+
await whenProtectedDataAvailable();
30+
const raw = await SecureStore.getItemAsync(storageKey);
31+
const value: unknown = raw === null ? [] : JSON.parse(raw);
32+
return new Set(
33+
Array.isArray(value) ? value.filter((id): id is string => typeof id === "string") : [],
34+
);
35+
} catch {
36+
return new Set();
37+
}
38+
}
39+
40+
/**
41+
* Tells the user, once per environment, that a paired session still carries
42+
* the legacy permission set. App-lifetime; presents one dialog at a time.
43+
*/
44+
export function installPermissionUpdateNotice(): () => void {
45+
let dismissed: Set<string> | null = null;
46+
const shownThisLaunch = new Set<string>();
47+
let showing = false;
48+
let disposed = false;
49+
50+
const presentNext = () => {
51+
if (disposed || dismissed === null || showing) return;
52+
const known = dismissed;
53+
const environment = appAtomRegistry
54+
.get(legacyPermissionEnvironmentsAtom)
55+
.find(
56+
({ environmentId }) => !known.has(environmentId) && !shownThisLaunch.has(environmentId),
57+
);
58+
if (!environment) return;
59+
showing = true;
60+
shownThisLaunch.add(environment.environmentId);
61+
const dismiss = () => {
62+
known.add(environment.environmentId);
63+
showing = false;
64+
void SecureStore.setItemAsync(storageKey, JSON.stringify([...known])).catch(() => {});
65+
presentNext();
66+
};
67+
Dialog.alert(
68+
`Permissions have changed for ${environment.label}`,
69+
"This connection still uses the old permissions, so some actions may no longer be available. Pair again using a new link with the permissions you need.",
70+
[{ text: "Got it", onPress: dismiss }],
71+
{ cancelable: false },
72+
);
73+
};
74+
75+
const unsubscribe = appAtomRegistry.subscribe(legacyPermissionEnvironmentsAtom, presentNext, {
76+
immediate: true,
77+
});
78+
void loadDismissedEnvironmentIds().then((ids) => {
79+
dismissed = ids;
80+
presentNext();
81+
});
82+
return () => {
83+
disposed = true;
84+
unsubscribe();
85+
};
86+
}

‎apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx‎

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScroll
33
import * as Application from "expo-application";
44
import Constants from "expo-constants";
55
import * as Updates from "expo-updates";
6-
import { useEffect, useState } from "react";
6+
import { useAtomValue } from "@effect/atom-react";
7+
import * as Effect from "effect/Effect";
8+
import { AsyncResult, Atom } from "effect/reactivity";
9+
import { useState } from "react";
710
import { View } from "react-native";
811
import { useSafeAreaInsets } from "react-native-safe-area-context";
912

@@ -27,6 +30,31 @@ type CrashLogState =
2730
| { readonly status: "unavailable" }
2831
| { readonly status: "ready"; readonly records: ReadonlyArray<StartupCrashRecord> };
2932

33+
// Not kept alive: each visit to the screen re-reads the log.
34+
const crashLogAtom = Atom.make(
35+
Effect.tryPromise(() => Updates.readLogEntriesAsync(LOG_WINDOW_MS)).pipe(
36+
Effect.map((entries): CrashLogState => ({
37+
status: "ready",
38+
records: parseStartupCrashRecords(entries),
39+
})),
40+
Effect.catch((error) =>
41+
Effect.sync((): CrashLogState => {
42+
console.warn("[diagnostics] could not read the expo-updates log", error);
43+
return { status: "unavailable" };
44+
}),
45+
),
46+
),
47+
).pipe(Atom.withLabel("mobile:diagnostics-crash-log"));
48+
49+
const UNAVAILABLE_CRASH_LOG_ATOM = Atom.make(
50+
AsyncResult.success<CrashLogState>({ status: "unavailable" }),
51+
);
52+
53+
function useCrashLogState(): CrashLogState {
54+
const result = useAtomValue(Updates.isEnabled ? crashLogAtom : UNAVAILABLE_CRASH_LOG_ATOM);
55+
return AsyncResult.isSuccess(result) ? result.value : { status: "loading" };
56+
}
57+
3058
function appIdentity() {
3159
return {
3260
version: Constants.expoConfig?.version ?? "0.0.0",
@@ -38,28 +66,9 @@ function appIdentity() {
3866

3967
export function SettingsDiagnosticsRouteScreen() {
4068
const insets = useSafeAreaInsets();
41-
const [state, setState] = useState<CrashLogState>(() =>
42-
Updates.isEnabled ? { status: "loading" } : { status: "unavailable" },
43-
);
69+
const state = useCrashLogState();
4470
const [copied, setCopied] = useState(false);
4571

46-
useEffect(() => {
47-
if (!Updates.isEnabled) return;
48-
let cancelled = false;
49-
Updates.readLogEntriesAsync(LOG_WINDOW_MS)
50-
.then((entries) => {
51-
if (cancelled) return;
52-
setState({ status: "ready", records: parseStartupCrashRecords(entries) });
53-
})
54-
.catch((error: unknown) => {
55-
console.warn("[diagnostics] could not read the expo-updates log", error);
56-
if (!cancelled) setState({ status: "unavailable" });
57-
});
58-
return () => {
59-
cancelled = true;
60-
};
61-
}, []);
62-
6372
const records = state.status === "ready" ? state.records : [];
6473
const copyReport = async () => {
6574
const ok = await tryCopyTextWithHaptic(formatStartupCrashReport(records, appIdentity()), {

0 commit comments

Comments
 (0)