Skip to content
TypeScript

refactor(mobile): settings and usage screens drop sync effects (#25227)

Julius Marminged593081034ee
diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx
index 8b444aa08f4..f3ade720277 100644
--- a/apps/mobile/src/App.tsx
+++ b/apps/mobile/src/App.tsx
@@ -1,4 +1,4 @@
-import { PermissionUpdateNotice } from "./features/connection/PermissionUpdateNotice";
+import { installPermissionUpdateNotice } from "./features/connection/permissionUpdateNotice";
import * as Linking from "expo-linking";
import * as SplashScreen from "expo-splash-screen";
import { useEffect } from "react";
@@ -31,6 +31,12 @@ import { environmentThreadShells } from "./state/threads";
import { environmentShell } from "./state/shell";
import { OverlayPortalHost } from "./components/ui/OverlayPortal";
import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
+import { hasCloudPublicConfig } from "./features/cloud/publicConfig";
+import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state";
+import {
+ disposeOnFoundationReplace,
+ type FoundationHotModule,
+} from "./lib/foundation-fast-refresh";
import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";
import { useUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc";
import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator";
@@ -58,7 +64,7 @@ void hydrateWorkspaceSelections();
const appLinking = {
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
config: { initialRouteName: "Home" },
- filter: shouldHandleAppLink,
+ filter: (url: string) => shouldHandleAppLink(url, hasCloudPublicConfig()),
getInitialURL: async () => (await Linking.getInitialURL()) ?? (await launchWorkspaceURL()),
getActionFromState: (
state: Parameters<typeof getActionFromState>[0],
@@ -68,15 +74,25 @@ const appLinking = {
(workspaceDetailLinkAction(state) as ReturnType<typeof getActionFromState>) ??
getActionFromState(state, options),
getStateFromPath: (path: string, options: Parameters<typeof getStateFromPath>[1]) =>
- restoreSettingsLinkState(
- restoreDraftLinkState(getStateFromPath(path, options), path),
- settingsLinkPage(),
+ takeScheduledTaskNewLink(
+ restoreSettingsLinkState(
+ restoreDraftLinkState(getStateFromPath(path, options), path),
+ settingsLinkPage(),
+ ),
),
};
const Navigation = createStaticNavigation(RootStack);
const navigationRef = createNavigationContainerRef();
+declare const module: { readonly hot?: FoundationHotModule } | undefined;
+
+const disposePermissionUpdateNotice = installPermissionUpdateNotice();
+disposeOnFoundationReplace(
+ typeof module === "undefined" ? undefined : module.hot,
+ disposePermissionUpdateNotice,
+);
+
function SplashScreenCoordinator() {
const { isReady } = useAppearancePreferences();
@@ -119,7 +135,6 @@ function AppContent() {
<>
<SplashScreenCoordinator />
<SubscriptionUsageCoordinator />
- <PermissionUpdateNotice />
<GestureHandlerRootView className="flex-1">
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
diff --git a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx
index 32ec03bf38a..4d0b340317c 100644
--- a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx
+++ b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx
@@ -5,8 +5,8 @@ import { Button } from "../../components/ui/Button";
import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
import { useAuth } from "@clerk/expo";
-import { StackActions, useNavigation } from "@react-navigation/native";
-import { useEffect, useState } from "react";
+import { useNavigation } from "@react-navigation/native";
+import { useState } from "react";
import { Platform, RefreshControl, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -19,21 +19,9 @@ import { useConnectionController } from "../connection/useConnectionController";
import { optOutOfConnectOnboarding } from "./connectOnboardingOptOut";
import { hasCloudPublicConfig } from "./publicConfig";
+// Only reachable with cloud config: onboarding is requested after a T3 Connect
+// sign-in, and appLinking drops the deep link otherwise.
export function ConnectOnboardingRouteScreen() {
- const navigation = useNavigation();
-
- // Without cloud config, deep links must exit to avoid an empty, undismissable sheet.
- useEffect(() => {
- if (hasCloudPublicConfig()) {
- return;
- }
- if (navigation.canGoBack()) {
- navigation.goBack();
- } else {
- navigation.dispatch(StackActions.replace("Home"));
- }
- }, [navigation]);
-
return hasCloudPublicConfig() ? <ConfiguredConnectOnboardingRouteScreen /> : null;
}
diff --git a/apps/mobile/src/features/connection/PermissionUpdateNotice.tsx b/apps/mobile/src/features/connection/PermissionUpdateNotice.tsx
deleted file mode 100644
index ce1f0b901a9..00000000000
--- a/apps/mobile/src/features/connection/PermissionUpdateNotice.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import * as Dialog from "../../components/ui/Dialog";
-import { useAtomValue } from "@effect/atom-react";
-import { sessionHasLegacyPermissions } from "@t3tools/contracts";
-import { Atom } from "effect/reactivity";
-import * as SecureStore from "expo-secure-store";
-import { useEffect, useMemo, useRef, useState } from "react";
-
-import { whenProtectedDataAvailable } from "../../lib/protectedData";
-import { useEnvironments } from "../../state/environments";
-import { environmentSession } from "../../state/session";
-
-const storageKey = "t3code.permission-update.v1";
-const dismissedThisLaunch = new Set<string>();
-const shownThisLaunch = new Set<string>();
-
-export function PermissionUpdateNotice() {
- const { environments } = useEnvironments();
- const [dismissed, setDismissed] = useState<ReadonlySet<string> | null>(null);
- const showing = useRef(false);
- const affected = useAtomValue(
- useMemo(
- () =>
- Atom.make((get) =>
- environments.filter(({ environmentId }) => {
- const session = get(environmentSession.sessionStateAtom(environmentId));
- return (
- session._tag === "Success" &&
- !session.waiting &&
- sessionHasLegacyPermissions(session.value)
- );
- }),
- ),
- [environments],
- ),
- );
-
- useEffect(() => {
- let active = true;
- void whenProtectedDataAvailable()
- .then(() => SecureStore.getItemAsync(storageKey))
- .then((raw) => {
- const value: unknown = raw === null ? [] : JSON.parse(raw);
- if (active)
- setDismissed(
- new Set(
- Array.isArray(value)
- ? value.filter((id): id is string => typeof id === "string")
- : [],
- ),
- );
- })
- .catch(() => {
- if (active) setDismissed(new Set());
- });
- return () => {
- active = false;
- };
- }, []);
-
- useEffect(() => {
- if (dismissed === null || showing.current) return;
- const environment = affected.find(
- ({ environmentId }) => !dismissed.has(environmentId) && !shownThisLaunch.has(environmentId),
- );
- if (!environment) return;
- showing.current = true;
- shownThisLaunch.add(environment.environmentId);
- const dismiss = () => {
- dismissedThisLaunch.add(environment.environmentId);
- const next = new Set([...dismissed, ...dismissedThisLaunch]);
- showing.current = false;
- setDismissed(next);
- void SecureStore.setItemAsync(storageKey, JSON.stringify([...next])).catch(() => {});
- };
- Dialog.alert(
- `Permissions have changed for ${environment.label}`,
- "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.",
- [{ text: "Got it", onPress: dismiss }],
- { cancelable: false },
- );
- }, [affected, dismissed]);
- return null;
-}
diff --git a/apps/mobile/src/features/connection/permissionUpdateNotice.ts b/apps/mobile/src/features/connection/permissionUpdateNotice.ts
new file mode 100644
index 00000000000..d35952f0c0e
--- /dev/null
+++ b/apps/mobile/src/features/connection/permissionUpdateNotice.ts
@@ -0,0 +1,86 @@
+import * as Dialog from "../../components/ui/Dialog";
+import { sessionHasLegacyPermissions } from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
+import * as SecureStore from "expo-secure-store";
+
+import { whenProtectedDataAvailable } from "../../lib/protectedData";
+import { appAtomRegistry } from "../../state/atom-registry";
+import { projectEnvironmentPresentation } from "../../state/environments";
+import { environmentPresentations } from "../../state/presentation";
+import { environmentSession } from "../../state/session";
+
+const storageKey = "t3code.permission-update.v1";
+
+const legacyPermissionEnvironmentsAtom = Atom.make((get) =>
+ [...get(environmentPresentations.presentationsAtom).entries()].flatMap(
+ ([environmentId, presentation]) => {
+ const session = get(environmentSession.sessionStateAtom(environmentId));
+ return session._tag === "Success" &&
+ !session.waiting &&
+ sessionHasLegacyPermissions(session.value)
+ ? [projectEnvironmentPresentation(environmentId, presentation)]
+ : [];
+ },
+ ),
+).pipe(Atom.withLabel("mobile:legacy-permission-environments"));
+
+async function loadDismissedEnvironmentIds(): Promise<Set<string>> {
+ try {
+ await whenProtectedDataAvailable();
+ const raw = await SecureStore.getItemAsync(storageKey);
+ const value: unknown = raw === null ? [] : JSON.parse(raw);
+ return new Set(
+ Array.isArray(value) ? value.filter((id): id is string => typeof id === "string") : [],
+ );
+ } catch {
+ return new Set();
+ }
+}
+
+/**
+ * Tells the user, once per environment, that a paired session still carries
+ * the legacy permission set. App-lifetime; presents one dialog at a time.
+ */
+export function installPermissionUpdateNotice(): () => void {
+ let dismissed: Set<string> | null = null;
+ const shownThisLaunch = new Set<string>();
+ let showing = false;
+ let disposed = false;
+
+ const presentNext = () => {
+ if (disposed || dismissed === null || showing) return;
+ const known = dismissed;
+ const environment = appAtomRegistry
+ .get(legacyPermissionEnvironmentsAtom)
+ .find(
+ ({ environmentId }) => !known.has(environmentId) && !shownThisLaunch.has(environmentId),
+ );
+ if (!environment) return;
+ showing = true;
+ shownThisLaunch.add(environment.environmentId);
+ const dismiss = () => {
+ known.add(environment.environmentId);
+ showing = false;
+ void SecureStore.setItemAsync(storageKey, JSON.stringify([...known])).catch(() => {});
+ presentNext();
+ };
+ Dialog.alert(
+ `Permissions have changed for ${environment.label}`,
+ "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.",
+ [{ text: "Got it", onPress: dismiss }],
+ { cancelable: false },
+ );
+ };
+
+ const unsubscribe = appAtomRegistry.subscribe(legacyPermissionEnvironmentsAtom, presentNext, {
+ immediate: true,
+ });
+ void loadDismissedEnvironmentIds().then((ids) => {
+ dismissed = ids;
+ presentNext();
+ });
+ return () => {
+ disposed = true;
+ unsubscribe();
+ };
+}
diff --git a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
index 2473813c5ff..41872729346 100644
--- a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
+++ b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
@@ -3,7 +3,10 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScroll
import * as Application from "expo-application";
import Constants from "expo-constants";
import * as Updates from "expo-updates";
-import { useEffect, useState } from "react";
+import { useAtomValue } from "@effect/atom-react";
+import * as Effect from "effect/Effect";
+import { AsyncResult, Atom } from "effect/reactivity";
+import { useState } from "react";
import { View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -27,6 +30,31 @@ type CrashLogState =
| { readonly status: "unavailable" }
| { readonly status: "ready"; readonly records: ReadonlyArray<StartupCrashRecord> };
+// Not kept alive: each visit to the screen re-reads the log.
+const crashLogAtom = Atom.make(
+ Effect.tryPromise(() => Updates.readLogEntriesAsync(LOG_WINDOW_MS)).pipe(
+ Effect.map((entries): CrashLogState => ({
+ status: "ready",
+ records: parseStartupCrashRecords(entries),
+ })),
+ Effect.catch((error) =>
+ Effect.sync((): CrashLogState => {
+ console.warn("[diagnostics] could not read the expo-updates log", error);
+ return { status: "unavailable" };
+ }),
+ ),
+ ),
+).pipe(Atom.withLabel("mobile:diagnostics-crash-log"));
+
+const UNAVAILABLE_CRASH_LOG_ATOM = Atom.make(
+ AsyncResult.success<CrashLogState>({ status: "unavailable" }),
+);
+
+function useCrashLogState(): CrashLogState {
+ const result = useAtomValue(Updates.isEnabled ? crashLogAtom : UNAVAILABLE_CRASH_LOG_ATOM);
+ return AsyncResult.isSuccess(result) ? result.value : { status: "loading" };
+}
+
function appIdentity() {
return {
version: Constants.expoConfig?.version ?? "0.0.0",
@@ -38,28 +66,9 @@ function appIdentity() {
export function SettingsDiagnosticsRouteScreen() {
const insets = useSafeAreaInsets();
- const [state, setState] = useState<CrashLogState>(() =>
- Updates.isEnabled ? { status: "loading" } : { status: "unavailable" },
- );
+ const state = useCrashLogState();
const [copied, setCopied] = useState(false);
- useEffect(() => {
- if (!Updates.isEnabled) return;
- let cancelled = false;
- Updates.readLogEntriesAsync(LOG_WINDOW_MS)
- .then((entries) => {
- if (cancelled) return;
- setState({ status: "ready", records: parseStartupCrashRecords(entries) });
- })
- .catch((error: unknown) => {
- console.warn("[diagnostics] could not read the expo-updates log", error);
- if (!cancelled) setState({ status: "unavailable" });
- });
- return () => {
- cancelled = true;
- };
- }, []);
-
const records = state.status === "ready" ? state.records : [];
const copyReport = async () => {
const ok = await tryCopyTextWithHaptic(formatStartupCrashReport(records, appIdentity()), {
diff --git a/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx
index 09c94c95a6c..5267130b1b3 100644
--- a/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx
@@ -2,12 +2,13 @@ import * as Dialog from "../../components/ui/Dialog";
import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
import Constants from "expo-constants";
import { settlePromise } from "@t3tools/client-runtime/state/runtime";
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import { Pressable, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/ui/AppText";
import { SymbolView } from "../../components/ui/AppSymbol";
+import { useDeadlinePassed } from "../../lib/clock";
import {
type AppUpdateCheckState,
isAppUpdateCheckAvailable,
@@ -37,7 +38,14 @@ export function SettingsAboutRouteScreen() {
}
function AppSettingsSection() {
- const [updateState, setUpdateState] = useState<AppUpdateCheckState>("idle");
+ const [checkState, setCheckState] = useState<{
+ readonly state: AppUpdateCheckState;
+ // "Up to date" is a confirmation that fades back to idle.
+ readonly settledUntil: number | null;
+ }>({ state: "idle", settledUntil: null });
+ const confirmationExpired = useDeadlinePassed(checkState.settledUntil);
+ const updateState =
+ checkState.state === "current" && confirmationExpired ? "idle" : checkState.state;
const updateInFlight = useRef(false);
const hiddenUpdateTapCount = useRef(0);
@@ -50,12 +58,6 @@ function AppSettingsSection() {
const busy =
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
- useEffect(() => {
- if (updateState !== "current") return;
- const timer = setTimeout(() => setUpdateState("idle"), 3000);
- return () => clearTimeout(timer);
- }, [updateState]);
-
async function checkForUpdate() {
// disabled updates next render; the ref blocks same-frame double taps.
if (updateInFlight.current) return;
@@ -65,7 +67,11 @@ function AppSettingsSection() {
runAppUpdateCheck({
applyMode: "immediate",
onFailure: (message) => Dialog.alert("Update failed", message),
- onStateChange: setUpdateState,
+ onStateChange: (state) =>
+ setCheckState({
+ state,
+ settledUntil: state === "current" ? Date.now() + 3000 : null,
+ }),
}),
);
updateInFlight.current = false;
diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx
index ff806c53ec0..433a353e99c 100644
--- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx
@@ -5,7 +5,7 @@ import {
UserProfileView,
} from "@clerk/expo/native-components";
import { useNavigation } from "@react-navigation/native";
-import { useEffect, useLayoutEffect, useState } from "react";
+import { useEffect, useState } from "react";
import { View } from "react-native";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
@@ -20,15 +20,8 @@ const USER_PROFILE_CUSTOM_PAGES = [
},
] satisfies UserProfileCustomPage[];
+// Without cloud config the app has no entry point here and appLinking drops the deep link.
export function SettingsAuthRouteScreen() {
- const navigation = useNavigation();
-
- useLayoutEffect(() => {
- if (!hasCloudPublicConfig()) {
- navigation.goBack();
- }
- }, [navigation]);
-
return hasCloudPublicConfig() ? <ConfiguredSettingsAuthRouteScreen /> : null;
}
@@ -41,6 +34,8 @@ function ConfiguredSettingsAuthRouteScreen() {
const [hasBeenSignedIn, setHasBeenSignedIn] = useState(isSignedIn === true);
if (isSignedIn && !hasBeenSignedIn) setHasBeenSignedIn(true);
+ // Clerk reports sign-out only through its auth store (the native profile view
+ // and the T3 Connect page can both sign out), so this follows that store.
useEffect(() => {
if (hasBeenSignedIn && isLoaded && isSignedIn === false) {
navigation.goBack();
diff --git a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
index 997e1683f07..c252ddd81b3 100644
--- a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
@@ -12,7 +12,7 @@ import {
import { deriveProjectGroupLabel } from "@t3tools/client-runtime/state/project-grouping";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { useNavigation } from "@react-navigation/native";
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import { Platform, Pressable, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -58,15 +58,16 @@ export function SettingsProjectOverviewRouteScreen() {
setIsRemoving(false);
};
const navigation = useNavigation();
- const { selectedTargets, projectGroups, selectedProjectKey, selectProject } =
- useSettingsEnvironmentFilter();
- const latestProjectKey = useRef(selectedProjectKey);
- useEffect(() => {
- latestProjectKey.current = selectedProjectKey;
- }, [selectedProjectKey]);
+ const {
+ selectedTargets,
+ projectGroups,
+ selectedProjectKey,
+ selectProject,
+ getSelectedProjectKey,
+ } = useSettingsEnvironmentFilter();
// The filter can move to another project while a removal is still running.
const finishProjectRemoval = (projectKey: string | null) => {
- if (latestProjectKey.current !== projectKey) return;
+ if (getSelectedProjectKey() !== projectKey) return;
if (navigation.isFocused())
leaveSettingsPage(navigation, workspaceHasColumns(), DEFAULT_SETTINGS_PAGE);
// Otherwise the filter keeps pointing at the removed project as an unavailable one.
diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
index 99d3fa658cf..bc768b32ff8 100644
--- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
@@ -32,7 +32,7 @@ import {
WEBHOOK_FILTER_OPS,
type WebhookFilterDraft,
} from "@t3tools/client-runtime/scheduled-task-webhook";
-import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { useRef, useState, type ReactNode } from "react";
import { useFocusEffect, useNavigation, usePreventRemove } from "@react-navigation/native";
import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
import { AppState, Platform, Pressable, TextInput as RNTextInput, View } from "react-native";
@@ -78,7 +78,11 @@ import {
} from "./scheduledTaskDraft";
import { settingsTargetsForProject } from "./settings-environment-filter.logic";
import { useScheduledTaskEditor } from "./scheduled-task-editor";
-import { scheduledTaskEditorSessionAtom } from "./scheduled-task-editor-state";
+import {
+ discardScheduledTaskEditor,
+ markScheduledTaskEditorSaved,
+ scheduledTaskEditorSessionAtom,
+} from "./scheduled-task-editor-state";
import { appAtomRegistry } from "../../state/atom-registry";
import {
formatNextScheduledTaskRun,
@@ -449,15 +453,9 @@ export function SettingsScheduledTasksRouteScreen() {
);
}
+// The "New task" action and takeScheduledTaskNewLink clear the editor before
+// this screen opens, so it starts from the default target.
export function SettingsScheduledTaskNewRouteScreen() {
- const { resetEditor } = useScheduledTaskEditor();
- const { availableTargets } = useSettingsEnvironmentFilter();
- const initialized = useRef(false);
- useLayoutEffect(() => {
- if (initialized.current || availableTargets.length === 0) return;
- initialized.current = true;
- resetEditor();
- }, [availableTargets.length, resetEditor]);
return <SettingsScheduledTaskEditorScreen title="New scheduled task" />;
}
@@ -466,20 +464,14 @@ export function SettingsScheduledTaskEditRouteScreen() {
}
function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }) {
- const {
- editor,
- voiceOwnerKey,
- readEditor,
- setEditor,
- startEditor,
- hasChanges,
- draftForEnvironment,
- } = useScheduledTaskEditor();
+ const { editor, voiceOwnerKey, readEditor, setEditor, hasChanges, draftForEnvironment } =
+ useScheduledTaskEditor();
const { availableTargets } = useSettingsEnvironmentFilter();
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const [saving, setSaving] = useState(false);
- const [saved, setSaved] = useState(false);
+ // Set once the save lands, so the removal guard lets the editor close.
+ const saved = useRef(false);
const ownerKey = editor ? `${voiceOwnerKey}:${editor.environmentId}` : null;
const prompt = editor?.draft.prompt ?? "";
const [selectionState, setSelectionState] = useState<{
@@ -518,8 +510,12 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }
},
disabled: saving,
});
- const preventRemove = !saved && (hasChanges || saving);
+ const preventRemove = hasChanges || saving;
usePreventRemove(preventRemove, ({ data }) => {
+ if (saved.current) {
+ navigation.dispatch(data.action);
+ return;
+ }
if (saving) {
Dialog.alert("Saving task", "Wait for the task to finish saving before leaving.");
return;
@@ -531,19 +527,12 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }
style: "destructive",
onPress: () => {
if (voiceInput.isBusy) voiceInput.cancel();
- startEditor(null);
+ discardScheduledTaskEditor();
navigation.dispatch(data.action);
},
},
]);
});
- useEffect(() => {
- if (!saved) return;
- const frame = requestAnimationFrame(() => {
- if (navigation.isFocused()) navigation.goBack();
- });
- return () => cancelAnimationFrame(frame);
- }, [navigation, saved]);
return (
<SettingsScreen title={title}>
{Platform.OS === "ios" ? (
@@ -599,7 +588,11 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }
setDraft={(draft) => {
if (!saving) setEditor({ ...editor, draft });
}}
- onSaved={() => setSaved(true)}
+ onSaved={() => {
+ saved.current = true;
+ markScheduledTaskEditorSaved();
+ if (navigation.isFocused()) navigation.goBack();
+ }}
onChangeEnvironment={(target) => {
if (target.environmentId === editor.environmentId) return;
setEditor({
diff --git a/apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx b/apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx
index 58def043185..54819d25b14 100644
--- a/apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx
@@ -1,6 +1,6 @@
import { SheetCloseButton } from "../../../components/ui/SheetHeader";
-import { type NavigationProp, type ParamListBase, useNavigation } from "@react-navigation/native";
-import { useCallback, useLayoutEffect, useState } from "react";
+import { useNavigation } from "@react-navigation/native";
+import { useState } from "react";
import { Linking, Pressable, View } from "react-native";
import { WebView } from "react-native-webview";
@@ -10,6 +10,7 @@ import { AppActivityIndicator } from "../../../components/ui/AppActivityIndicato
import { AppText as Text } from "../../../components/ui/AppText";
import { LoadingStrip } from "../../../components/ui/LoadingStrip";
import { SymbolView } from "../../../components/ui/AppSymbol";
+import { NativeStackScreenOptions } from "../../../native/StackHeader";
import { isLegalDocumentUrl, LEGAL_URL } from "../lib/legal-document-url";
export function SettingsLegalDocumentCloseHeaderButton() {
@@ -39,6 +40,10 @@ export function SettingsLegalDocumentExternalHeaderButton({
);
}
+function externalHeaderButton(externalUrl: string) {
+ return () => <SettingsLegalDocumentExternalHeaderButton externalUrl={externalUrl} />;
+}
+
interface SettingsLegalDocumentRouteScreenProps {
readonly documentName: string;
readonly documentUrl: string;
@@ -48,28 +53,26 @@ export function SettingsLegalDocumentRouteScreen({
documentName,
documentUrl,
}: SettingsLegalDocumentRouteScreenProps) {
- const navigation = useNavigation<NavigationProp<ParamListBase>>();
const [reloadKey, setReloadKey] = useState(0);
const [loadProgress, setLoadProgress] = useState(0);
const [loadError, setLoadError] = useState<string | null>(null);
const [externalUrl, setExternalUrl] = useState(documentUrl);
- const renderExternalHeaderButton = useCallback(
- () => <SettingsLegalDocumentExternalHeaderButton externalUrl={externalUrl} />,
- [externalUrl],
+ const headerOptions = (
+ <NativeStackScreenOptions
+ options={{
+ headerRight: externalHeaderButton(externalUrl),
+ }}
+ optionsVersion={externalUrl}
+ />
);
- useLayoutEffect(() => {
- navigation.setOptions({
- headerRight: renderExternalHeaderButton,
- });
- }, [navigation, renderExternalHeaderButton]);
-
- const openExternalUrl = useCallback((url: string) => {
+ const openExternalUrl = (url: string) => {
void Linking.openURL(url).catch(() => undefined);
- }, []);
+ };
if (loadError) {
return (
<View className="flex-1 items-center justify-center gap-4 bg-sheet px-8">
+ {headerOptions}
<SymbolView
name="exclamationmark.triangle"
size={32}
@@ -109,6 +112,7 @@ export function SettingsLegalDocumentRouteScreen({
return (
<View className="relative flex-1 bg-sheet">
+ {headerOptions}
{loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
<WebView
key={reloadKey}
diff --git a/apps/mobile/src/features/settings/scheduled-task-editor-state.test.ts b/apps/mobile/src/features/settings/scheduled-task-editor-state.test.ts
index 97a7d38a44b..4171f49607a 100644
--- a/apps/mobile/src/features/settings/scheduled-task-editor-state.test.ts
+++ b/apps/mobile/src/features/settings/scheduled-task-editor-state.test.ts
@@ -4,9 +4,12 @@ import { afterEach, describe, expect, it } from "vite-plus/test";
import { appAtomRegistry } from "../../state/atom-registry";
import { createDraft } from "./scheduledTaskDraft";
import {
+ discardScheduledTaskEditor,
+ markScheduledTaskEditorSaved,
readScheduledTaskEditor,
scheduledTaskEditorSessionAtom,
startScheduledTaskEditor,
+ takeScheduledTaskNewLink,
updateScheduledTaskEditor,
} from "./scheduled-task-editor-state";
@@ -55,3 +58,61 @@ describe("scheduled task voice draft", () => {
expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current).toBeNull();
});
});
+
+describe("new scheduled task link", () => {
+ const editing = {
+ environmentId: EnvironmentId.make("environment"),
+ environmentLabel: "Environment",
+ draft: createDraft(null, null),
+ };
+ const newTaskLink = {
+ routes: [
+ { name: "Home" },
+ {
+ name: "SettingsSheet",
+ state: {
+ routes: [{ name: "SettingsScheduledTasks" }, { name: "SettingsScheduledTaskNew" }],
+ },
+ },
+ ],
+ };
+
+ it("drops the last edited task so the new-task screen starts from the default", () => {
+ startScheduledTaskEditor(editing);
+ expect(takeScheduledTaskNewLink(newTaskLink)).toBe(newTaskLink);
+ expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)).toBeNull();
+ });
+
+ it("keeps unsaved changes until the editor's removal guard discards them", () => {
+ startScheduledTaskEditor(editing);
+ const edited = { ...editing, draft: { ...editing.draft, prompt: "unsaved" } };
+ updateScheduledTaskEditor(edited, null);
+
+ takeScheduledTaskNewLink(newTaskLink);
+ expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current).toBe(edited);
+
+ discardScheduledTaskEditor();
+ expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)).toBeNull();
+ });
+
+ it("starts the new-task screen fresh after the edited task was saved", () => {
+ startScheduledTaskEditor(editing);
+ updateScheduledTaskEditor({ ...editing, draft: { ...editing.draft, prompt: "saved" } }, null);
+ markScheduledTaskEditorSaved();
+
+ takeScheduledTaskNewLink(newTaskLink);
+ expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)).toBeNull();
+ });
+
+ it("closes a discarded editor as empty when no new-task link is waiting", () => {
+ startScheduledTaskEditor(editing);
+ discardScheduledTaskEditor();
+ expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current).toBeNull();
+ });
+
+ it("keeps the editor for links to other screens", () => {
+ startScheduledTaskEditor(editing);
+ takeScheduledTaskNewLink({ routes: [{ name: "SettingsSheet" }] });
+ expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current).toBe(editing);
+ });
+});
diff --git a/apps/mobile/src/features/settings/scheduled-task-editor-state.ts b/apps/mobile/src/features/settings/scheduled-task-editor-state.ts
index a0ab412a834..73b8b1da727 100644
--- a/apps/mobile/src/features/settings/scheduled-task-editor-state.ts
+++ b/apps/mobile/src/features/settings/scheduled-task-editor-state.ts
@@ -1,8 +1,11 @@
import type { EnvironmentId } from "@t3tools/contracts";
+import type { NavigationState, PartialState } from "@react-navigation/native";
import { Atom } from "effect/reactivity";
+import { findLinkedRoute } from "../../lib/appLinking";
+
import { appAtomRegistry } from "../../state/atom-registry";
-import type { ScheduledTaskDraft } from "./scheduledTaskDraft";
+import { hasScheduledTaskDraftChanges, type ScheduledTaskDraft } from "./scheduledTaskDraft";
export type ScheduledTaskEditor = {
readonly environmentId: EnvironmentId;
@@ -20,8 +23,22 @@ export const scheduledTaskEditorSessionAtom = Atom.make<ScheduledTaskEditorSessi
null,
).pipe(Atom.keepAlive);
let nextEditorId = 0;
+let newTaskLinkAwaitsDiscard = false;
+
+export function scheduledTaskEditorHasChanges(
+ initial: ScheduledTaskEditor | null,
+ current: ScheduledTaskEditor | null,
+): boolean {
+ return Boolean(
+ initial &&
+ current &&
+ (initial.environmentId !== current.environmentId ||
+ hasScheduledTaskDraftChanges(initial.draft, current.draft)),
+ );
+}
export function startScheduledTaskEditor(next: ScheduledTaskEditor | null): void {
+ newTaskLinkAwaitsDiscard = false;
appAtomRegistry.set(scheduledTaskEditorSessionAtom, {
id: ++nextEditorId,
initial: next,
@@ -45,6 +62,18 @@ export function updateScheduledTaskEditor(
});
}
+/**
+ * A saved task is the new baseline. Without it a later new-task link reads the saved edits as
+ * unsaved, keeps them under "New", and saving there would overwrite the task.
+ */
+export function markScheduledTaskEditorSaved(): void {
+ newTaskLinkAwaitsDiscard = false;
+ const session = appAtomRegistry.get(scheduledTaskEditorSessionAtom);
+ if (session) {
+ appAtomRegistry.set(scheduledTaskEditorSessionAtom, { ...session, initial: session.current });
+ }
+}
+
export function readScheduledTaskEditor(
voiceOwnerKey: string,
defaultEditor: ScheduledTaskEditor | null,
@@ -53,3 +82,32 @@ export function readScheduledTaskEditor(
if (`scheduled-task:${session?.id ?? 0}` !== voiceOwnerKey) return null;
return session ? session.current : defaultEditor;
}
+
+/**
+ * A new-task link starts a fresh editor, or a warm app reopens the last task's draft under
+ * "New" and saves over it. Links parse before the open editor's removal guard runs, so
+ * unsaved changes stay until the user discards them there.
+ */
+export function takeScheduledTaskNewLink(
+ state: PartialState<NavigationState> | undefined,
+): PartialState<NavigationState> | undefined {
+ if (findLinkedRoute(state, ["SettingsScheduledTaskNew"])) {
+ const session = appAtomRegistry.get(scheduledTaskEditorSessionAtom);
+ if (session && scheduledTaskEditorHasChanges(session.initial, session.current)) {
+ newTaskLinkAwaitsDiscard = true;
+ } else {
+ appAtomRegistry.set(scheduledTaskEditorSessionAtom, null);
+ }
+ }
+ return state;
+}
+
+/** Drops unsaved changes; a new-task link that waited on them then opens a fresh editor. */
+export function discardScheduledTaskEditor(): void {
+ if (newTaskLinkAwaitsDiscard) {
+ newTaskLinkAwaitsDiscard = false;
+ appAtomRegistry.set(scheduledTaskEditorSessionAtom, null);
+ return;
+ }
+ startScheduledTaskEditor(null);
+}
diff --git a/apps/mobile/src/features/settings/scheduled-task-editor.tsx b/apps/mobile/src/features/settings/scheduled-task-editor.tsx
index b593a039fe3..75d602fdb57 100644
--- a/apps/mobile/src/features/settings/scheduled-task-editor.tsx
+++ b/apps/mobile/src/features/settings/scheduled-task-editor.tsx
@@ -3,15 +3,12 @@ import type { EnvironmentId } from "@t3tools/contracts";
import { useMemo, useCallback, type Dispatch, type SetStateAction } from "react";
import { useProjects, useServerConfigs } from "../../state/entities";
-import {
- createDraft,
- scheduledTaskDefaultModel,
- hasScheduledTaskDraftChanges,
-} from "./scheduledTaskDraft";
+import { createDraft, scheduledTaskDefaultModel } from "./scheduledTaskDraft";
import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
import { settingsTargetsForProject } from "./settings-environment-filter.logic";
import {
+ scheduledTaskEditorHasChanges,
scheduledTaskEditorSessionAtom,
startScheduledTaskEditor,
updateScheduledTaskEditor,
@@ -64,12 +61,7 @@ export function useScheduledTaskEditor() {
const voiceOwnerKey = `scheduled-task:${session?.id ?? 0}`;
const editor = session ? session.current : defaultEditor;
const initial = session ? session.initial : defaultEditor;
- const hasChanges = Boolean(
- initial &&
- editor &&
- (initial.environmentId !== editor.environmentId ||
- hasScheduledTaskDraftChanges(initial.draft, editor.draft)),
- );
+ const hasChanges = scheduledTaskEditorHasChanges(initial, editor);
const setEditor = useCallback<Dispatch<SetStateAction<ScheduledTaskEditor | null>>>(
(update) => {
updateScheduledTaskEditor(update, defaultEditor);
diff --git a/apps/mobile/src/features/settings/settings-environment-filter.tsx b/apps/mobile/src/features/settings/settings-environment-filter.tsx
index 8564c950da3..eddfea17950 100644
--- a/apps/mobile/src/features/settings/settings-environment-filter.tsx
+++ b/apps/mobile/src/features/settings/settings-environment-filter.tsx
@@ -2,8 +2,10 @@ import type { EnvironmentId } from "@t3tools/contracts";
import { buildProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
import {
createContext,
+ useCallback,
useContext,
useMemo,
+ useRef,
useState,
type Dispatch,
type ReactNode,
@@ -57,7 +59,9 @@ interface SettingsEnvironmentSelection {
readonly selectedIds: ReadonlySet<EnvironmentId> | null;
readonly selectedProjectKey: string | null;
readonly setSelectedIds: Dispatch<SetStateAction<ReadonlySet<EnvironmentId> | null>>;
- readonly setSelectedProjectKey: Dispatch<SetStateAction<string | null>>;
+ readonly selectProject: (projectKey: string | null) => void;
+ /** The selection as of now, for async work that outlives the render it started in. */
+ readonly getSelectedProjectKey: () => string | null;
}
const SettingsEnvironmentSelectionContext = createContext<SettingsEnvironmentSelection | null>(
@@ -76,13 +80,28 @@ export function SettingsEnvironmentFilterProvider(props: {
}) {
const [selectedIds, setSelectedIds] = useState<ReadonlySet<EnvironmentId> | null>(null);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
+ // Written only by selectProject, so it can keep a key that the close reset below cleared.
+ // Its one reader, a project removal that finishes after Settings closed, then clears an
+ // already empty selection, which is harmless.
+ const currentProjectKey = useRef<string | null>(null);
if (!props.open && (selectedIds !== null || selectedProjectKey !== null)) {
setSelectedIds(null);
setSelectedProjectKey(null);
}
+ const selectProject = useCallback((projectKey: string | null) => {
+ currentProjectKey.current = projectKey;
+ setSelectedProjectKey(projectKey);
+ }, []);
+ const getSelectedProjectKey = useCallback(() => currentProjectKey.current, []);
const value = useMemo(
- () => ({ selectedIds, selectedProjectKey, setSelectedIds, setSelectedProjectKey }),
- [selectedIds, selectedProjectKey],
+ () => ({
+ selectedIds,
+ selectedProjectKey,
+ setSelectedIds,
+ selectProject,
+ getSelectedProjectKey,
+ }),
+ [selectedIds, selectedProjectKey, selectProject, getSelectedProjectKey],
);
return (
<SettingsEnvironmentSelectionContext value={value}>
@@ -94,7 +113,8 @@ export function SettingsEnvironmentFilterProvider(props: {
export function useSettingsEnvironmentFilter() {
const selection = useContext(SettingsEnvironmentSelectionContext);
if (selection === null) throw new Error("Settings environment filter provider is missing.");
- const { selectedIds, selectedProjectKey, setSelectedIds, setSelectedProjectKey } = selection;
+ const { selectedIds, selectedProjectKey, setSelectedIds, selectProject, getSelectedProjectKey } =
+ selection;
const { environments } = useEnvironments();
const projects = useProjects();
const groupingSettings = useMobileProjectGroupingSettings();
@@ -125,7 +145,8 @@ export function useSettingsEnvironmentFilter() {
projectGroups,
selectableProjectGroups,
selectedProjectKey,
- selectProject: setSelectedProjectKey,
+ selectProject,
+ getSelectedProjectKey,
selectAll: () => setSelectedIds(null),
toggleEnvironment: (environmentId: EnvironmentId) =>
setSelectedIds((current) =>
@@ -140,7 +161,8 @@ export function useSettingsEnvironmentFilter() {
selectableProjectGroups,
selectedProjectKey,
setSelectedIds,
- setSelectedProjectKey,
+ selectProject,
+ getSelectedProjectKey,
],
);
}
diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.test.ts b/apps/mobile/src/features/usage/UsageLimitsSection.test.ts
deleted file mode 100644
index 3b0d5719fb7..00000000000
--- a/apps/mobile/src/features/usage/UsageLimitsSection.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import { EnvironmentId } from "@t3tools/contracts";
-import { beforeEach, expect, it, vi } from "vite-plus/test";
-
-const state = vi.hoisted(() => ({
- values: [] as unknown[],
- cursor: 0,
- presentations: new Map(),
- refreshProviders: vi.fn(),
- autoRefresh: async () => {},
- refreshingRef: { current: false },
-}));
-vi.mock("../../state/session", () => ({
- useEnvironmentScope: () => true,
- readEnvironmentScope: () => true,
-}));
-vi.mock("react", () => ({
- useState: (initial: unknown) => {
- const index = state.cursor++;
- if (!(index in state.values)) {
- state.values[index] = typeof initial === "function" ? initial() : initial;
- }
- return [
- state.values[index],
- (next: unknown) => {
- state.values[index] = typeof next === "function" ? next(state.values[index]) : next;
- },
- ];
- },
- useRef: () => state.refreshingRef,
- useEffect: () => {},
- useEffectEvent: (callback: () => Promise<void>) => {
- state.autoRefresh = callback;
- return callback;
- },
-}));
-vi.mock("@effect/atom-react", () => ({ useAtomValue: () => state.presentations }));
-vi.mock("react-native", () => ({ Alert: {}, Pressable: "button", View: "div" }));
-vi.mock("../../components/ui/AppText", () => ({ AppText: "span" }));
-vi.mock("../../components/ProviderIcon", () => ({ ProviderIcon: () => null }));
-vi.mock("./usageProviders", () => ({ useProviderColors: () => ({}) }));
-vi.mock("../../state/presentation", () => ({
- environmentPresentations: { presentationsAtom: null },
-}));
-vi.mock("../../state/server", () => ({ serverEnvironment: { refreshProviders: null } }));
-vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.refreshProviders }));
-
-import { useRefreshLimits } from "./UsageLimitsSection";
-import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
-
-beforeEach(() => {
- state.values = [];
- state.cursor = 0;
- state.refreshingRef.current = false;
- state.refreshProviders.mockReset();
-});
-
-it("keeps a newer environment failure when an older refresh finishes", async () => {
- const a = EnvironmentId.make("mobile-limits-a");
- const b = EnvironmentId.make("mobile-limits-b");
- const pending = Promise.withResolvers<{ _tag: string }>();
- const read = () => {
- state.cursor = 0;
- return useRefreshLimits();
- };
- const presentation = (label: string) => ({
- connection: { phase: "connected" },
- entry: { target: { label } },
- });
- state.presentations = new Map([[a, presentation("A")]]);
- state.refreshProviders.mockImplementation(({ environmentId }) =>
- environmentId === a ? pending.promise : Promise.resolve({ _tag: "Failure" }),
- );
- const first = read().refresh();
- state.presentations = new Map([
- [a, presentation("A")],
- [b, presentation("B")],
- ]);
- read();
- await state.autoRefresh();
- expect(read().failedLabels).toEqual(["B"]);
- pending.resolve({ _tag: "Success" });
- await first;
- expect(read().failedLabels).toEqual(["B"]);
-});
-
-it("does not let an older multi-environment batch clear a newer failure for the same environment", async () => {
- const a = EnvironmentId.make("mobile-limits-race-a");
- const b = EnvironmentId.make("mobile-limits-race-b");
- const aFirst = Promise.withResolvers<{ _tag: string }>();
- const bFirst = Promise.withResolvers<{ _tag: string }>();
- const read = (selected: ReadonlySet<EnvironmentId> | null = null) => {
- state.cursor = 0;
- return useRefreshLimits(selected);
- };
- const presentation = (label: string) => ({
- connection: { phase: "connected" },
- entry: { target: { label } },
- });
- state.presentations = new Map([
- [a, presentation("A")],
- [b, presentation("B")],
- ]);
- let aCalls = 0;
- state.refreshProviders.mockImplementation(({ environmentId }) =>
- environmentId === b
- ? bFirst.promise
- : ++aCalls === 1
- ? aFirst.promise
- : Promise.resolve({ _tag: "Failure" }),
- );
- read();
- const older = state.autoRefresh();
- aFirst.resolve({ _tag: "Success" });
- await refreshUsageLimits(a, () => aFirst.promise);
- const selected = new Set([a]);
- await read(selected).refresh();
- expect(read(selected).failedLabels).toEqual(["A"]);
- bFirst.resolve({ _tag: "Success" });
- await older;
- expect(read(selected).failedLabels).toEqual(["A"]);
-});
diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.tsx b/apps/mobile/src/features/usage/UsageLimitsSection.tsx
index 1ce31c382ee..3cd009cf67c 100644
--- a/apps/mobile/src/features/usage/UsageLimitsSection.tsx
+++ b/apps/mobile/src/features/usage/UsageLimitsSection.tsx
@@ -1,5 +1,5 @@
import * as Dialog from "../../components/ui/Dialog";
-import { useAtomValue } from "@effect/atom-react";
+import { RegistryContext, useAtomMount, useAtomValue } from "@effect/atom-react";
import {
AuthProvidersManageScope,
type EnvironmentId,
@@ -17,8 +17,8 @@ import {
paceRemainingPercent,
remainingPercent,
} from "@t3tools/shared/usageLimits";
-import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
-import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
+import { type ReactNode, useContext, useRef, useState } from "react";
+import { Atom } from "effect/reactivity";
import { Linking, Pressable, View } from "react-native";
import { AppText as Text } from "../../components/ui/AppText";
@@ -27,6 +27,13 @@ import { environmentPresentations } from "../../state/presentation";
import { serverEnvironment } from "../../state/server";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";
+import { useNowMinuteMs } from "../../lib/clock";
+import {
+ environmentIdsKey,
+ limitsAutoRefreshSetAtom,
+ limitsRefreshFailuresAtom,
+ refreshEnvironmentLimits,
+} from "./usageLimitsRefresh";
import { usageProviderKind, useProviderColors } from "./usageProviders";
const PACE_LABEL = { ahead: "ahead of pace", on: "on pace", under: "under pace" } as const;
@@ -308,79 +315,54 @@ export function ResetCredits(props: {
);
}
+const IDLE_ATOM = Atom.make(undefined);
+
export function useRefreshLimits(
selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
active = false,
) {
+ const registry = useContext(RegistryContext);
const presentations = useAtomValue(environmentPresentations.presentationsAtom);
- const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
- reportFailure: false,
- });
- const [now, setNow] = useState(() => Date.now());
+ const now = useNowMinuteMs();
const [refreshing, setRefreshing] = useState(false);
const refreshingRef = useRef(false);
- const [failedEnvironments, setFailedEnvironments] = useState<
- readonly { environmentId: EnvironmentId; label: string }[]
- >([]);
- const refresh = async (automatic = false, afterPending = false) => {
- const connected = [...presentations].filter(
- ([environmentId, presentation]) =>
- presentation.connection.phase === "connected" &&
- (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
+ const selected = [...presentations].filter(
+ ([environmentId]) =>
+ selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId),
+ );
+ const connectedIds = selected
+ .filter(([, presentation]) => presentation.connection.phase === "connected")
+ .map(([environmentId]) => environmentId);
+ const connectedKey = environmentIdsKey(connectedIds);
+ useAtomMount(active && connectedKey !== "" ? limitsAutoRefreshSetAtom(connectedKey) : IDLE_ATOM);
+ const failedIds = new Set(
+ useAtomValue(limitsRefreshFailuresAtom(environmentIdsKey(selected.map(([id]) => id)))),
+ );
+ const failedLabels = selected
+ .filter(([environmentId]) => failedIds.has(environmentId))
+ .map(([, presentation]) => presentation.entry.target.label);
+
+ const refresh = (afterPending: boolean) =>
+ Promise.all(
+ connectedIds.map((environmentId) =>
+ refreshEnvironmentLimits(registry, environmentId, { afterPending }),
+ ),
);
- await Promise.all(
- connected.map(async ([environmentId, presentation]) => {
- const result = await refreshUsageLimits(
- environmentId,
- () => refreshProviders({ environmentId, input: {} }),
- automatic,
- afterPending,
- );
- if (result === undefined) return;
- setFailedEnvironments((previous) => [
- ...previous.filter((failed) => failed.environmentId !== environmentId),
- ...(result._tag === "Failure"
- ? [{ environmentId, label: presentation.entry.target.label }]
- : []),
- ]);
- }),
- ).finally(() => setNow(Date.now()));
- };
// Android RefreshControl needs a true-to-false cycle to stop, even with nothing to probe.
const refreshManually = async () => {
if (refreshingRef.current) return;
refreshingRef.current = true;
setRefreshing(true);
- await refresh().finally(() => {
+ await refresh(false).finally(() => {
refreshingRef.current = false;
setRefreshing(false);
});
};
- const connectedLimitsEnvironments = [...presentations]
- .filter(
- ([environmentId, presentation]) =>
- presentation.connection.phase === "connected" &&
- (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
- )
- .map(([environmentId]) => environmentId)
- .sort()
- .join(",");
- const autoRefreshLimits = useEffectEvent(() => refresh(true));
- useEffect(() => {
- if (active && connectedLimitsEnvironments) void autoRefreshLimits();
- }, [active, connectedLimitsEnvironments]);
-
- const failedLabels = failedEnvironments
- .filter(
- ({ environmentId }) =>
- selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId),
- )
- .map(({ label }) => label);
return {
now,
refreshing,
failedLabels,
refresh: refreshManually,
- refreshAfterEnable: () => refresh(false, true),
+ refreshAfterEnable: () => refresh(true),
};
}
diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
index aa0209ebb1b..5e165cac5ff 100644
--- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx
+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
@@ -28,19 +28,13 @@ import {
formatUsd,
makeWindow,
} from "@t3tools/shared/usageFormat";
-import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { useRef, useState, type ReactNode } from "react";
import { Platform, Pressable, RefreshControl, View } from "react-native";
-import Animated, {
- FadeIn,
- ReduceMotion,
- useAnimatedStyle,
- useSharedValue,
- withDelay,
- withTiming,
-} from "react-native-reanimated";
+import Animated, { FadeIn, ReduceMotion } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { SegmentedControl } from "../../components/ui/SegmentedControl";
+import { useReduceMotionEnabled } from "../../lib/appState";
import { AppText as Text } from "../../components/ui/AppText";
import { ProviderIcon } from "../../components/ProviderIcon";
import { cn } from "../../lib/cn";
@@ -403,15 +397,14 @@ function UsageUpdating({
readonly label: string | null;
readonly children: ReactNode;
}) {
- const opacity = useSharedValue(1);
- useLayoutEffect(() => {
- opacity.set(
- dimmed
- ? withDelay(150, withTiming(0.5, { duration: 150, reduceMotion: ReduceMotion.System }))
- : withTiming(1, { duration: 150, reduceMotion: ReduceMotion.System }),
- );
- }, [opacity, dimmed]);
- const dimStyle = useAnimatedStyle(() => ({ opacity: opacity.get() }));
+ const reduceMotion = useReduceMotionEnabled();
+ // The delay keeps a quick refresh from flashing the content.
+ const dimStyle = {
+ opacity: dimmed ? 0.5 : 1,
+ transitionProperty: "opacity",
+ transitionDuration: reduceMotion ? 0 : 150,
+ transitionDelay: dimmed ? 150 : 0,
+ } as const;
return (
<View>
diff --git a/apps/mobile/src/features/usage/usageLimitsRefresh.test.ts b/apps/mobile/src/features/usage/usageLimitsRefresh.test.ts
new file mode 100644
index 00000000000..80310b98d8a
--- /dev/null
+++ b/apps/mobile/src/features/usage/usageLimitsRefresh.test.ts
@@ -0,0 +1,100 @@
+import { EnvironmentId } from "@t3tools/contracts";
+import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
+import * as Cause from "effect/Cause";
+import { AsyncResult, AtomRegistry } from "effect/reactivity";
+import { expect, it, vi } from "vite-plus/test";
+
+type RefreshResult = AsyncResult.AsyncResult<void, string>;
+
+const state = vi.hoisted(() => ({
+ refresh: (_environmentId: string): Promise<RefreshResult> => {
+ throw new Error("refresh not set up");
+ },
+}));
+vi.mock("../../state/server", () => ({
+ serverEnvironment: {
+ refreshProviders: {
+ label: "refresh providers",
+ run: (_registry: unknown, input: { readonly environmentId: string }) =>
+ state.refresh(input.environmentId),
+ },
+ },
+}));
+
+import {
+ environmentIdsKey,
+ limitsRefreshFailuresAtom,
+ refreshEnvironmentLimits,
+} from "./usageLimitsRefresh";
+
+const success: RefreshResult = AsyncResult.success(undefined);
+const failure: RefreshResult = AsyncResult.failure(Cause.fail("offline"));
+
+function setup(refresh: (environmentId: string) => Promise<RefreshResult>) {
+ state.refresh = refresh;
+ const registry = AtomRegistry.make();
+ return {
+ registry,
+ failures: (ids: readonly EnvironmentId[]) => {
+ const atom = limitsRefreshFailuresAtom(environmentIdsKey(ids));
+ registry.mount(atom);
+ return registry.get(atom);
+ },
+ };
+}
+
+it("keeps a newer environment failure when an older refresh finishes", async () => {
+ const a = EnvironmentId.make("mobile-limits-a");
+ const b = EnvironmentId.make("mobile-limits-b");
+ const pending = Promise.withResolvers<RefreshResult>();
+ const { registry, failures } = setup((environmentId) =>
+ environmentId === a ? pending.promise : Promise.resolve(failure),
+ );
+ failures([a, b]);
+ const first = refreshEnvironmentLimits(registry, a);
+ await refreshEnvironmentLimits(registry, b, { automatic: true });
+ expect(failures([a, b])).toEqual([b]);
+ pending.resolve(success);
+ await first;
+ expect(failures([a, b])).toEqual([b]);
+});
+
+it("does not let an older refresh clear a newer failure for the same environment", async () => {
+ const a = EnvironmentId.make("mobile-limits-race-a");
+ const b = EnvironmentId.make("mobile-limits-race-b");
+ const aFirst = Promise.withResolvers<RefreshResult>();
+ const bFirst = Promise.withResolvers<RefreshResult>();
+ let aCalls = 0;
+ const { registry, failures } = setup((environmentId) =>
+ environmentId === b
+ ? bFirst.promise
+ : ++aCalls === 1
+ ? aFirst.promise
+ : Promise.resolve(failure),
+ );
+ failures([a, b]);
+ const older = Promise.all([
+ refreshEnvironmentLimits(registry, a, { automatic: true }),
+ refreshEnvironmentLimits(registry, b, { automatic: true }),
+ ]);
+ aFirst.resolve(success);
+ await refreshUsageLimits(a, () => aFirst.promise);
+ await refreshEnvironmentLimits(registry, a);
+ expect(failures([a])).toEqual([a]);
+ bFirst.resolve(success);
+ await older;
+ expect(failures([a, b])).toEqual([a]);
+});
+
+it("skips an automatic refresh inside the throttle window without touching the outcome", async () => {
+ const a = EnvironmentId.make("mobile-limits-throttle");
+ const { registry, failures } = setup(() => Promise.resolve(failure));
+ failures([a]);
+ await refreshEnvironmentLimits(registry, a);
+ expect(failures([a])).toEqual([a]);
+ state.refresh = () => Promise.resolve(success);
+ await refreshEnvironmentLimits(registry, a, { automatic: true });
+ expect(failures([a])).toEqual([a]);
+ await refreshEnvironmentLimits(registry, a);
+ expect(failures([a])).toEqual([]);
+});
diff --git a/apps/mobile/src/features/usage/usageLimitsRefresh.ts b/apps/mobile/src/features/usage/usageLimitsRefresh.ts
new file mode 100644
index 00000000000..be8259c5f62
--- /dev/null
+++ b/apps/mobile/src/features/usage/usageLimitsRefresh.ts
@@ -0,0 +1,70 @@
+import { EnvironmentId } from "@t3tools/contracts";
+import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
+import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
+import { Atom, type AtomRegistry } from "effect/reactivity";
+
+import { serverEnvironment } from "../../state/server";
+
+/**
+ * Whether the last finished limits refresh for an environment failed. Not kept
+ * alive: the limits view mounts it, and leaving the view forgets old failures.
+ */
+export const limitsRefreshFailedAtom = Atom.family((environmentId: EnvironmentId) =>
+ Atom.make(false).pipe(Atom.withLabel(`mobile:limits-refresh-failed:${environmentId}`)),
+);
+
+export async function refreshEnvironmentLimits(
+ registry: AtomRegistry.AtomRegistry,
+ environmentId: EnvironmentId,
+ options: { readonly automatic?: boolean; readonly afterPending?: boolean } = {},
+): Promise<void> {
+ // One refresh runs per environment at a time, so results land in the order
+ // they were started and the newest outcome always wins.
+ const result = await refreshUsageLimits(
+ environmentId,
+ () =>
+ runAtomCommand(
+ registry,
+ serverEnvironment.refreshProviders,
+ { environmentId, input: {} },
+ { reportFailure: false },
+ ),
+ options.automatic,
+ options.afterPending,
+ );
+ if (result === undefined) return;
+ registry.set(limitsRefreshFailedAtom(environmentId), result._tag === "Failure");
+}
+
+// Mounting starts an automatic refresh, which refreshUsageLimits throttles to
+// one every few minutes per environment.
+const limitsAutoRefreshAtom = Atom.family((environmentId: EnvironmentId) =>
+ Atom.make((get) => {
+ void refreshEnvironmentLimits(get.registry, environmentId, { automatic: true });
+ }).pipe(Atom.withLabel(`mobile:limits-auto-refresh:${environmentId}`)),
+);
+
+export function environmentIdsKey(environmentIds: Iterable<EnvironmentId>): string {
+ return [...environmentIds].sort().join(",");
+}
+
+function splitEnvironmentIds(key: string): EnvironmentId[] {
+ return key === "" ? [] : key.split(",").map((id) => EnvironmentId.make(id));
+}
+
+/** Keyed by a sorted, comma-joined id list so equal selections share one atom. */
+export const limitsAutoRefreshSetAtom = Atom.family((environmentIds: string) =>
+ Atom.make((get) => {
+ for (const environmentId of splitEnvironmentIds(environmentIds)) {
+ get(limitsAutoRefreshAtom(environmentId));
+ }
+ }),
+);
+
+export const limitsRefreshFailuresAtom = Atom.family((environmentIds: string) =>
+ Atom.make((get) =>
+ splitEnvironmentIds(environmentIds).filter((environmentId) =>
+ get(limitsRefreshFailedAtom(environmentId)),
+ ),
+ ),
+);
diff --git a/apps/mobile/src/lib/appLinking.test.ts b/apps/mobile/src/lib/appLinking.test.ts
index 480f58e0daa..0fbf540a4d1 100644
--- a/apps/mobile/src/lib/appLinking.test.ts
+++ b/apps/mobile/src/lib/appLinking.test.ts
@@ -1,12 +1,12 @@
import { describe, expect, it } from "vite-plus/test";
-import { shouldHandleAppLink, restoreDraftLinkState } from "./appLinking";
+import { findLinkedRoute, restoreDraftLinkState, shouldHandleAppLink } from "./appLinking";
describe("shouldHandleAppLink", () => {
it.each(["t3code://", "t3code:///", "t3code-dev://", "t3code-preview://"])(
"ignores scheme-only URL %s",
(url) => {
- expect(shouldHandleAppLink(url)).toBe(false);
+ expect(shouldHandleAppLink(url, true)).toBe(false);
},
);
@@ -15,17 +15,41 @@ describe("shouldHandleAppLink", () => {
"t3code://pair?pairingUrl=x",
"t3code-dev://settings/usage?tab=limits",
])("handles path-bearing URL %s", (url) => {
- expect(shouldHandleAppLink(url)).toBe(true);
+ expect(shouldHandleAppLink(url, true)).toBe(true);
});
it.each(["t3code://expo-development-client/?url=x", "t3code://expo-sharing/anything"])(
"ignores lifecycle URL %s",
(url) => {
- expect(shouldHandleAppLink(url)).toBe(false);
+ expect(shouldHandleAppLink(url, true)).toBe(false);
},
);
});
+describe("cloud-only deep links", () => {
+ it.each([
+ "t3code://connect-onboarding",
+ "t3code-dev://connect-onboarding/?source=x",
+ "t3code://settings/waitlist",
+ "t3code://settings/auth",
+ "exp://192.168.1.2:8081/--/settings/auth",
+ ])("ignores %s without cloud config", (url) => {
+ expect(shouldHandleAppLink(url, false)).toBe(false);
+ expect(shouldHandleAppLink(url, true)).toBe(true);
+ });
+
+ it.each([
+ "t3code://settings",
+ "t3code://settings/authors",
+ "t3code://pair?next=settings/auth",
+ "t3code://threads/env/thread/files/scripts/connect-onboarding",
+ "t3code://new/draft/files/settings/auth",
+ "exp://192.168.1.2:8081/--/threads/env/thread/files/settings/waitlist",
+ ])("still handles %s without cloud config", (url) => {
+ expect(shouldHandleAppLink(url, false)).toBe(true);
+ });
+});
+
describe("draft deep links", () => {
it("opens the old draft URL on the thread screen with its draft identity", () => {
const draft = { projectId: "project-1", environmentId: "env-1", draftId: "draft-1" };
@@ -65,3 +89,28 @@ describe("draft deep links", () => {
expect(restoreDraftLinkState(undefined, "/new/draft")).toBeUndefined();
});
});
+
+describe("nested link routes", () => {
+ const settingsLink = {
+ routes: [
+ { name: "Home" },
+ {
+ name: "SettingsSheet",
+ state: {
+ routes: [
+ { name: "Settings" },
+ { name: "SettingsEnvironmentNew", params: { pairingUrl: "x", autoConnect: "1" } },
+ ],
+ },
+ },
+ ],
+ };
+
+ it("finds a route the link opens inside a nested navigator", () => {
+ expect(findLinkedRoute(settingsLink, ["SettingsEnvironmentNew"])?.params).toEqual({
+ pairingUrl: "x",
+ autoConnect: "1",
+ });
+ expect(findLinkedRoute(settingsLink, ["ConnectionsNew"])).toBeUndefined();
+ });
+});
diff --git a/apps/mobile/src/lib/appLinking.ts b/apps/mobile/src/lib/appLinking.ts
index 08263bb94d2..6f8e8953972 100644
--- a/apps/mobile/src/lib/appLinking.ts
+++ b/apps/mobile/src/lib/appLinking.ts
@@ -6,14 +6,24 @@ import type { NavigationState, PartialState } from "@react-navigation/native";
* the launcher, not app navigation. Without this filter it falls through
* to the NotFound wildcard route on every dev launch.
*/
-export function shouldHandleAppLink(url: string): boolean {
+export function shouldHandleAppLink(url: string, cloudConfigured: boolean): boolean {
return (
!url.includes("expo-development-client") &&
!url.includes("://expo-sharing") &&
- !/^t3code(-dev|-preview)?:\/*$/.test(url)
+ !/^t3code(-dev|-preview)?:\/*$/.test(url) &&
+ (cloudConfigured || !CLOUD_ONLY_LINK_PATH.test(url.split(/[?#]/)[0] ?? ""))
);
}
+/**
+ * Screens that only exist with T3 Connect configured. A build without it has
+ * no entry points to them, so a link must not open one empty. Anchored to the
+ * app-relative path (after `exp://host/--/` in Expo Go) so a file route whose
+ * path merely ends in one of these names still opens.
+ */
+const CLOUD_ONLY_LINK_PATH =
+ /^[a-z][\w+.-]*:\/*(?:[^/]*\/--\/)?(?:connect-onboarding|settings\/(?:auth|waitlist))\/*$/i;
+
/** Keep the published draft URLs while using the root thread screen. */
export function restoreDraftLinkState(
state: PartialState<NavigationState> | undefined,
@@ -29,3 +39,23 @@ export function restoreDraftLinkState(
if (pathname !== "new/draft") routes.push(target);
return { ...state, index: routes.length - 1, routes };
}
+
+type LinkState = PartialState<NavigationState>;
+type LinkRoute = LinkState["routes"][number];
+
+function isLinkState(value: unknown): value is LinkState {
+ return typeof value === "object" && value !== null && Array.isArray((value as LinkState).routes);
+}
+
+/** The first route named one of `names`, at any nesting depth of a parsed link. */
+export function findLinkedRoute(
+ state: LinkState | undefined,
+ names: ReadonlyArray<string>,
+): LinkRoute | undefined {
+ for (const route of state?.routes ?? []) {
+ if (names.includes(route.name)) return route;
+ const nested = isLinkState(route.state) ? findLinkedRoute(route.state, names) : undefined;
+ if (nested) return nested;
+ }
+ return undefined;
+}
diff --git a/apps/mobile/src/lib/clock.test.ts b/apps/mobile/src/lib/clock.test.ts
new file mode 100644
index 00000000000..a72efe95e36
--- /dev/null
+++ b/apps/mobile/src/lib/clock.test.ts
@@ -0,0 +1,9 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { minuteTickToEpochMs } from "./clock";
+
+describe("minuteTickToEpochMs", () => {
+ it("reads the minute tick as UTC regardless of the device timezone", () => {
+ expect(minuteTickToEpochMs("2026-10-26T02:14")).toBe(Date.UTC(2026, 9, 26, 2, 14));
+ });
+});
diff --git a/apps/mobile/src/lib/clock.ts b/apps/mobile/src/lib/clock.ts
index 47227cda2d8..0bdbb8ee1db 100644
--- a/apps/mobile/src/lib/clock.ts
+++ b/apps/mobile/src/lib/clock.ts
@@ -1,4 +1,4 @@
-import { deadlineStore } from "@t3tools/client-runtime/clock";
+import { deadlineStore, minuteTick } from "@t3tools/client-runtime/clock";
import { useSyncExternalStore } from "react";
/** Re-renders once when `deadlineMs` (epoch ms) is reached; `null` never passes. */
@@ -6,3 +6,18 @@ export function useDeadlinePassed(deadlineMs: number | null): boolean {
const store = deadlineStore(deadlineMs);
return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
}
+
+/**
+ * `minuteTick`'s UTC `YYYY-MM-DDTHH:mm` as epoch ms. The snapshot carries no
+ * offset, and `Date.parse` reads offset-less date-times as local time.
+ */
+export function minuteTickToEpochMs(minute: string): number {
+ return Date.parse(`${minute}:00Z`);
+}
+
+/** Epoch ms floored to the minute, advancing each wall-clock minute. */
+export function useNowMinuteMs(): number {
+ return minuteTickToEpochMs(
+ useSyncExternalStore(minuteTick.subscribe, minuteTick.getSnapshot, minuteTick.getSnapshot),
+ );
+}
diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts
index bdb05cb1d29..70a232bb9d0 100644
--- a/apps/mobile/src/state/use-remote-environment-registry.ts
+++ b/apps/mobile/src/state/use-remote-environment-registry.ts
@@ -6,6 +6,7 @@ import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/reactivity";
import { useCallback } from "react";
+import { hasCloudPublicConfig } from "../features/cloud/publicConfig";
import { useConnectionController } from "../features/connection/useConnectionController";
import { environmentPresentations } from "./presentation";
import { useWorkspaceConnectionState, useWorkspaceEnvironments } from "./workspace";
@@ -182,10 +183,15 @@ export function useRemoteConnections() {
`Forget ${environment.environmentLabel} and its cached threads on this device.\n\nIt stays on your T3 Connect account and keeps its host space. Deregister it under T3 Account → T3 Connect to free it.`,
[
{ text: "Cancel", style: "cancel" },
- {
- text: "Open T3 Account",
- onPress: () => navigation.navigate("SettingsAuth"),
- },
+ // SettingsAuth renders nothing in builds without cloud config.
+ ...(hasCloudPublicConfig()
+ ? [
+ {
+ text: "Open T3 Account",
+ onPress: () => navigation.navigate("SettingsAuth"),
+ },
+ ]
+ : []),
remove,
],
);