@devries-cameron20 / t3code-1 / commits / d593081034
Fork 0

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

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

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

Julius Marminge committed Oct 25, 2026 at 20:59 UTC d593081034ee04e2de56346a169e07ad7cc22dd9
24 files changed +699 -419
apps/mobile/src/App.tsx
+21 -6
@@ -1,4 +1,4 @@
1 -import { PermissionUpdateNotice } from "./features/connection/PermissionUpdateNotice";
1 +import { installPermissionUpdateNotice } from "./features/connection/permissionUpdateNotice";
2 import * as Linking from "expo-linking";
3 import * as SplashScreen from "expo-splash-screen";
4 import { useEffect } from "react";
@@ -31,6 +31,12 @@ import { environmentThreadShells } from "./state/threads";
31 import { environmentShell } from "./state/shell";
32 import { OverlayPortalHost } from "./components/ui/OverlayPortal";
33 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";
40 import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";
41 import { useUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc";
42 import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator";
@@ -58,7 +64,7 @@ void hydrateWorkspaceSelections();
64 const appLinking = {
65 prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
66 config: { initialRouteName: "Home" },
61 - filter: shouldHandleAppLink,
67 + filter: (url: string) => shouldHandleAppLink(url, hasCloudPublicConfig()),
68 getInitialURL: async () => (await Linking.getInitialURL()) ?? (await launchWorkspaceURL()),
69 getActionFromState: (
70 state: Parameters<typeof getActionFromState>[0],
@@ -68,15 +74,25 @@ const appLinking = {
74 (workspaceDetailLinkAction(state) as ReturnType<typeof getActionFromState>) ??
75 getActionFromState(state, options),
76 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 + ),
82 ),
83 };
84
85 const Navigation = createStaticNavigation(RootStack);
86 const navigationRef = createNavigationContainerRef();
87
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 +
96 function SplashScreenCoordinator() {
97 const { isReady } = useAppearancePreferences();
98
@@ -119,7 +135,6 @@ function AppContent() {
135 <>
136 <SplashScreenCoordinator />
137 <SubscriptionUsageCoordinator />
122 - <PermissionUpdateNotice />
138 <GestureHandlerRootView className="flex-1">
139 <KeyboardProvider statusBarTranslucent>
140 <SafeAreaProvider>
apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx
+4 -16
@@ -5,8 +5,8 @@ import { Button } from "../../components/ui/Button";
5 import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
6
7 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";
10 import { Platform, RefreshControl, View } from "react-native";
11 import { useSafeAreaInsets } from "react-native-safe-area-context";
12
@@ -19,21 +19,9 @@ import { useConnectionController } from "../connection/useConnectionController";
19 import { optOutOfConnectOnboarding } from "./connectOnboardingOptOut";
20 import { hasCloudPublicConfig } from "./publicConfig";
21
22 +// Only reachable with cloud config: onboarding is requested after a T3 Connect
23 +// sign-in, and appLinking drops the deep link otherwise.
24 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 -
25 return hasCloudPublicConfig() ? <ConfiguredConnectOnboardingRouteScreen /> : null;
26 }
27
apps/mobile/src/features/connection/PermissionUpdateNotice.tsx deleted
-83
@@ -1,83 +0,0 @@
1 -import * as Dialog from "../../components/ui/Dialog";
2 -import { useAtomValue } from "@effect/atom-react";
3 -import { sessionHasLegacyPermissions } from "@t3tools/contracts";
4 -import { Atom } from "effect/reactivity";
5 -import * as SecureStore from "expo-secure-store";
6 -import { useEffect, useMemo, useRef, useState } from "react";
7 -
8 -import { whenProtectedDataAvailable } from "../../lib/protectedData";
9 -import { useEnvironments } from "../../state/environments";
10 -import { environmentSession } from "../../state/session";
11 -
12 -const storageKey = "t3code.permission-update.v1";
13 -const dismissedThisLaunch = new Set<string>();
14 -const shownThisLaunch = new Set<string>();
15 -
16 -export function PermissionUpdateNotice() {
17 - const { environments } = useEnvironments();
18 - const [dismissed, setDismissed] = useState<ReadonlySet<string> | null>(null);
19 - const showing = useRef(false);
20 - const affected = useAtomValue(
21 - useMemo(
22 - () =>
23 - Atom.make((get) =>
24 - environments.filter(({ environmentId }) => {
25 - const session = get(environmentSession.sessionStateAtom(environmentId));
26 - return (
27 - session._tag === "Success" &&
28 - !session.waiting &&
29 - sessionHasLegacyPermissions(session.value)
30 - );
31 - }),
32 - ),
33 - [environments],
34 - ),
35 - );
36 -
37 - useEffect(() => {
38 - let active = true;
39 - void whenProtectedDataAvailable()
40 - .then(() => SecureStore.getItemAsync(storageKey))
41 - .then((raw) => {
42 - const value: unknown = raw === null ? [] : JSON.parse(raw);
43 - if (active)
44 - setDismissed(
45 - new Set(
46 - Array.isArray(value)
47 - ? value.filter((id): id is string => typeof id === "string")
48 - : [],
49 - ),
50 - );
51 - })
52 - .catch(() => {
53 - if (active) setDismissed(new Set());
54 - });
55 - return () => {
56 - active = false;
57 - };
58 - }, []);
59 -
60 - useEffect(() => {
61 - if (dismissed === null || showing.current) return;
62 - const environment = affected.find(
63 - ({ environmentId }) => !dismissed.has(environmentId) && !shownThisLaunch.has(environmentId),
64 - );
65 - if (!environment) return;
66 - showing.current = true;
67 - shownThisLaunch.add(environment.environmentId);
68 - const dismiss = () => {
69 - dismissedThisLaunch.add(environment.environmentId);
70 - const next = new Set([...dismissed, ...dismissedThisLaunch]);
71 - showing.current = false;
72 - setDismissed(next);
73 - void SecureStore.setItemAsync(storageKey, JSON.stringify([...next])).catch(() => {});
74 - };
75 - Dialog.alert(
76 - `Permissions have changed for ${environment.label}`,
77 - "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.",
78 - [{ text: "Got it", onPress: dismiss }],
79 - { cancelable: false },
80 - );
81 - }, [affected, dismissed]);
82 - return null;
83 -}
apps/mobile/src/features/connection/permissionUpdateNotice.ts new
+86
@@ -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
+30 -21
@@ -3,7 +3,10 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScroll
3 import * as Application from "expo-application";
4 import Constants from "expo-constants";
5 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";
10 import { View } from "react-native";
11 import { useSafeAreaInsets } from "react-native-safe-area-context";
12
@@ -27,6 +30,31 @@ type CrashLogState =
30 | { readonly status: "unavailable" }
31 | { readonly status: "ready"; readonly records: ReadonlyArray<StartupCrashRecord> };
32
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 +
58 function appIdentity() {
59 return {
60 version: Constants.expoConfig?.version ?? "0.0.0",
@@ -38,28 +66,9 @@ function appIdentity() {
66
67 export function SettingsDiagnosticsRouteScreen() {
68 const insets = useSafeAreaInsets();
41 - const [state, setState] = useState<CrashLogState>(() =>
42 - Updates.isEnabled ? { status: "loading" } : { status: "unavailable" },
43 - );
69 + const state = useCrashLogState();
70 const [copied, setCopied] = useState(false);
71
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 -
72 const records = state.status === "ready" ? state.records : [];
73 const copyReport = async () => {
74 const ok = await tryCopyTextWithHaptic(formatStartupCrashReport(records, appIdentity()), {
apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx
+15 -9
@@ -2,12 +2,13 @@ import * as Dialog from "../../components/ui/Dialog";
2 import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
3 import Constants from "expo-constants";
4 import { settlePromise } from "@t3tools/client-runtime/state/runtime";
5 -import { useEffect, useRef, useState } from "react";
5 +import { useRef, useState } from "react";
6 import { Pressable, View } from "react-native";
7 import { useSafeAreaInsets } from "react-native-safe-area-context";
8
9 import { AppText as Text } from "../../components/ui/AppText";
10 import { SymbolView } from "../../components/ui/AppSymbol";
11 +import { useDeadlinePassed } from "../../lib/clock";
12 import {
13 type AppUpdateCheckState,
14 isAppUpdateCheckAvailable,
@@ -37,7 +38,14 @@ export function SettingsAboutRouteScreen() {
38 }
39
40 function AppSettingsSection() {
40 - const [updateState, setUpdateState] = useState<AppUpdateCheckState>("idle");
41 + const [checkState, setCheckState] = useState<{
42 + readonly state: AppUpdateCheckState;
43 + // "Up to date" is a confirmation that fades back to idle.
44 + readonly settledUntil: number | null;
45 + }>({ state: "idle", settledUntil: null });
46 + const confirmationExpired = useDeadlinePassed(checkState.settledUntil);
47 + const updateState =
48 + checkState.state === "current" && confirmationExpired ? "idle" : checkState.state;
49 const updateInFlight = useRef(false);
50 const hiddenUpdateTapCount = useRef(0);
51
@@ -50,12 +58,6 @@ function AppSettingsSection() {
58 const busy =
59 updateState === "checking" || updateState === "downloading" || updateState === "restarting";
60
53 - useEffect(() => {
54 - if (updateState !== "current") return;
55 - const timer = setTimeout(() => setUpdateState("idle"), 3000);
56 - return () => clearTimeout(timer);
57 - }, [updateState]);
58 -
61 async function checkForUpdate() {
62 // disabled updates next render; the ref blocks same-frame double taps.
63 if (updateInFlight.current) return;
@@ -65,7 +67,11 @@ function AppSettingsSection() {
67 runAppUpdateCheck({
68 applyMode: "immediate",
69 onFailure: (message) => Dialog.alert("Update failed", message),
68 - onStateChange: setUpdateState,
70 + onStateChange: (state) =>
71 + setCheckState({
72 + state,
73 + settledUntil: state === "current" ? Date.now() + 3000 : null,
74 + }),
75 }),
76 );
77 updateInFlight.current = false;
apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx
+4 -9
@@ -5,7 +5,7 @@ import {
5 UserProfileView,
6 } from "@clerk/expo/native-components";
7 import { useNavigation } from "@react-navigation/native";
8 -import { useEffect, useLayoutEffect, useState } from "react";
8 +import { useEffect, useState } from "react";
9 import { View } from "react-native";
10
11 import { hasCloudPublicConfig } from "../cloud/publicConfig";
@@ -20,15 +20,8 @@ const USER_PROFILE_CUSTOM_PAGES = [
20 },
21 ] satisfies UserProfileCustomPage[];
22
23 +// Without cloud config the app has no entry point here and appLinking drops the deep link.
24 export function SettingsAuthRouteScreen() {
24 - const navigation = useNavigation();
25 -
26 - useLayoutEffect(() => {
27 - if (!hasCloudPublicConfig()) {
28 - navigation.goBack();
29 - }
30 - }, [navigation]);
31 -
25 return hasCloudPublicConfig() ? <ConfiguredSettingsAuthRouteScreen /> : null;
26 }
27
@@ -41,6 +34,8 @@ function ConfiguredSettingsAuthRouteScreen() {
34 const [hasBeenSignedIn, setHasBeenSignedIn] = useState(isSignedIn === true);
35 if (isSignedIn && !hasBeenSignedIn) setHasBeenSignedIn(true);
36
37 + // Clerk reports sign-out only through its auth store (the native profile view
38 + // and the T3 Connect page can both sign out), so this follows that store.
39 useEffect(() => {
40 if (hasBeenSignedIn && isLoaded && isSignedIn === false) {
41 navigation.goBack();
apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
+9 -8
@@ -12,7 +12,7 @@ import {
12 import { deriveProjectGroupLabel } from "@t3tools/client-runtime/state/project-grouping";
13 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
14 import { useNavigation } from "@react-navigation/native";
15 -import { useEffect, useRef, useState } from "react";
15 +import { useRef, useState } from "react";
16 import { Platform, Pressable, View } from "react-native";
17 import { useSafeAreaInsets } from "react-native-safe-area-context";
18
@@ -58,15 +58,16 @@ export function SettingsProjectOverviewRouteScreen() {
58 setIsRemoving(false);
59 };
60 const navigation = useNavigation();
61 - const { selectedTargets, projectGroups, selectedProjectKey, selectProject } =
62 - useSettingsEnvironmentFilter();
63 - const latestProjectKey = useRef(selectedProjectKey);
64 - useEffect(() => {
65 - latestProjectKey.current = selectedProjectKey;
66 - }, [selectedProjectKey]);
61 + const {
62 + selectedTargets,
63 + projectGroups,
64 + selectedProjectKey,
65 + selectProject,
66 + getSelectedProjectKey,
67 + } = useSettingsEnvironmentFilter();
68 // The filter can move to another project while a removal is still running.
69 const finishProjectRemoval = (projectKey: string | null) => {
69 - if (latestProjectKey.current !== projectKey) return;
70 + if (getSelectedProjectKey() !== projectKey) return;
71 if (navigation.isFocused())
72 leaveSettingsPage(navigation, workspaceHasColumns(), DEFAULT_SETTINGS_PAGE);
73 // Otherwise the filter keeps pointing at the removed project as an unavailable one.
apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+23 -30
@@ -32,7 +32,7 @@ import {
32 WEBHOOK_FILTER_OPS,
33 type WebhookFilterDraft,
34 } from "@t3tools/client-runtime/scheduled-task-webhook";
35 -import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
35 +import { useRef, useState, type ReactNode } from "react";
36 import { useFocusEffect, useNavigation, usePreventRemove } from "@react-navigation/native";
37 import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
38 import { AppState, Platform, Pressable, TextInput as RNTextInput, View } from "react-native";
@@ -78,7 +78,11 @@ import {
78 } from "./scheduledTaskDraft";
79 import { settingsTargetsForProject } from "./settings-environment-filter.logic";
80 import { useScheduledTaskEditor } from "./scheduled-task-editor";
81 -import { scheduledTaskEditorSessionAtom } from "./scheduled-task-editor-state";
81 +import {
82 + discardScheduledTaskEditor,
83 + markScheduledTaskEditorSaved,
84 + scheduledTaskEditorSessionAtom,
85 +} from "./scheduled-task-editor-state";
86 import { appAtomRegistry } from "../../state/atom-registry";
87 import {
88 formatNextScheduledTaskRun,
@@ -449,15 +453,9 @@ export function SettingsScheduledTasksRouteScreen() {
453 );
454 }
455
456 +// The "New task" action and takeScheduledTaskNewLink clear the editor before
457 +// this screen opens, so it starts from the default target.
458 export function SettingsScheduledTaskNewRouteScreen() {
453 - const { resetEditor } = useScheduledTaskEditor();
454 - const { availableTargets } = useSettingsEnvironmentFilter();
455 - const initialized = useRef(false);
456 - useLayoutEffect(() => {
457 - if (initialized.current || availableTargets.length === 0) return;
458 - initialized.current = true;
459 - resetEditor();
460 - }, [availableTargets.length, resetEditor]);
459 return <SettingsScheduledTaskEditorScreen title="New scheduled task" />;
460 }
461
@@ -466,20 +464,14 @@ export function SettingsScheduledTaskEditRouteScreen() {
464 }
465
466 function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }) {
469 - const {
470 - editor,
471 - voiceOwnerKey,
472 - readEditor,
473 - setEditor,
474 - startEditor,
475 - hasChanges,
476 - draftForEnvironment,
477 - } = useScheduledTaskEditor();
467 + const { editor, voiceOwnerKey, readEditor, setEditor, hasChanges, draftForEnvironment } =
468 + useScheduledTaskEditor();
469 const { availableTargets } = useSettingsEnvironmentFilter();
470 const navigation = useNavigation();
471 const insets = useSafeAreaInsets();
472 const [saving, setSaving] = useState(false);
482 - const [saved, setSaved] = useState(false);
473 + // Set once the save lands, so the removal guard lets the editor close.
474 + const saved = useRef(false);
475 const ownerKey = editor ? `${voiceOwnerKey}:${editor.environmentId}` : null;
476 const prompt = editor?.draft.prompt ?? "";
477 const [selectionState, setSelectionState] = useState<{
@@ -518,8 +510,12 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }
510 },
511 disabled: saving,
512 });
521 - const preventRemove = !saved && (hasChanges || saving);
513 + const preventRemove = hasChanges || saving;
514 usePreventRemove(preventRemove, ({ data }) => {
515 + if (saved.current) {
516 + navigation.dispatch(data.action);
517 + return;
518 + }
519 if (saving) {
520 Dialog.alert("Saving task", "Wait for the task to finish saving before leaving.");
521 return;
@@ -531,19 +527,12 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }
527 style: "destructive",
528 onPress: () => {
529 if (voiceInput.isBusy) voiceInput.cancel();
534 - startEditor(null);
530 + discardScheduledTaskEditor();
531 navigation.dispatch(data.action);
532 },
533 },
534 ]);
535 });
540 - useEffect(() => {
541 - if (!saved) return;
542 - const frame = requestAnimationFrame(() => {
543 - if (navigation.isFocused()) navigation.goBack();
544 - });
545 - return () => cancelAnimationFrame(frame);
546 - }, [navigation, saved]);
536 return (
537 <SettingsScreen title={title}>
538 {Platform.OS === "ios" ? (
@@ -599,7 +588,11 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }
588 setDraft={(draft) => {
589 if (!saving) setEditor({ ...editor, draft });
590 }}
602 - onSaved={() => setSaved(true)}
591 + onSaved={() => {
592 + saved.current = true;
593 + markScheduledTaskEditorSaved();
594 + if (navigation.isFocused()) navigation.goBack();
595 + }}
596 onChangeEnvironment={(target) => {
597 if (target.environmentId === editor.environmentId) return;
598 setEditor({
apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx
+18 -14
@@ -1,6 +1,6 @@
1 import { SheetCloseButton } from "../../../components/ui/SheetHeader";
2 -import { type NavigationProp, type ParamListBase, useNavigation } from "@react-navigation/native";
3 -import { useCallback, useLayoutEffect, useState } from "react";
2 +import { useNavigation } from "@react-navigation/native";
3 +import { useState } from "react";
4 import { Linking, Pressable, View } from "react-native";
5 import { WebView } from "react-native-webview";
6
@@ -10,6 +10,7 @@ import { AppActivityIndicator } from "../../../components/ui/AppActivityIndicato
10 import { AppText as Text } from "../../../components/ui/AppText";
11 import { LoadingStrip } from "../../../components/ui/LoadingStrip";
12 import { SymbolView } from "../../../components/ui/AppSymbol";
13 +import { NativeStackScreenOptions } from "../../../native/StackHeader";
14 import { isLegalDocumentUrl, LEGAL_URL } from "../lib/legal-document-url";
15
16 export function SettingsLegalDocumentCloseHeaderButton() {
@@ -39,6 +40,10 @@ export function SettingsLegalDocumentExternalHeaderButton({
40 );
41 }
42
43 +function externalHeaderButton(externalUrl: string) {
44 + return () => <SettingsLegalDocumentExternalHeaderButton externalUrl={externalUrl} />;
45 +}
46 +
47 interface SettingsLegalDocumentRouteScreenProps {
48 readonly documentName: string;
49 readonly documentUrl: string;
@@ -48,28 +53,26 @@ export function SettingsLegalDocumentRouteScreen({
53 documentName,
54 documentUrl,
55 }: SettingsLegalDocumentRouteScreenProps) {
51 - const navigation = useNavigation<NavigationProp<ParamListBase>>();
56 const [reloadKey, setReloadKey] = useState(0);
57 const [loadProgress, setLoadProgress] = useState(0);
58 const [loadError, setLoadError] = useState<string | null>(null);
59 const [externalUrl, setExternalUrl] = useState(documentUrl);
56 - const renderExternalHeaderButton = useCallback(
57 - () => <SettingsLegalDocumentExternalHeaderButton externalUrl={externalUrl} />,
58 - [externalUrl],
60 + const headerOptions = (
61 + <NativeStackScreenOptions
62 + options={{
63 + headerRight: externalHeaderButton(externalUrl),
64 + }}
65 + optionsVersion={externalUrl}
66 + />
67 );
68
61 - useLayoutEffect(() => {
62 - navigation.setOptions({
63 - headerRight: renderExternalHeaderButton,
64 - });
65 - }, [navigation, renderExternalHeaderButton]);
66 -
67 - const openExternalUrl = useCallback((url: string) => {
69 + const openExternalUrl = (url: string) => {
70 void Linking.openURL(url).catch(() => undefined);
69 - }, []);
71 + };
72 if (loadError) {
73 return (
74 <View className="flex-1 items-center justify-center gap-4 bg-sheet px-8">
75 + {headerOptions}
76 <SymbolView
77 name="exclamationmark.triangle"
78 size={32}
@@ -109,6 +112,7 @@ export function SettingsLegalDocumentRouteScreen({
112
113 return (
114 <View className="relative flex-1 bg-sheet">
115 + {headerOptions}
116 {loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
117 <WebView
118 key={reloadKey}
apps/mobile/src/features/settings/scheduled-task-editor-state.test.ts
+61
@@ -4,9 +4,12 @@ import { afterEach, describe, expect, it } from "vite-plus/test";
4 import { appAtomRegistry } from "../../state/atom-registry";
5 import { createDraft } from "./scheduledTaskDraft";
6 import {
7 + discardScheduledTaskEditor,
8 + markScheduledTaskEditorSaved,
9 readScheduledTaskEditor,
10 scheduledTaskEditorSessionAtom,
11 startScheduledTaskEditor,
12 + takeScheduledTaskNewLink,
13 updateScheduledTaskEditor,
14 } from "./scheduled-task-editor-state";
15
@@ -55,3 +58,61 @@ describe("scheduled task voice draft", () => {
58 expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current).toBeNull();
59 });
60 });
61 +
62 +describe("new scheduled task link", () => {
63 + const editing = {
64 + environmentId: EnvironmentId.make("environment"),
65 + environmentLabel: "Environment",
66 + draft: createDraft(null, null),
67 + };
68 + const newTaskLink = {
69 + routes: [
70 + { name: "Home" },
71 + {
72 + name: "SettingsSheet",
73 + state: {
74 + routes: [{ name: "SettingsScheduledTasks" }, { name: "SettingsScheduledTaskNew" }],
75 + },
76 + },
77 + ],
78 + };
79 +
80 + it("drops the last edited task so the new-task screen starts from the default", () => {
81 + startScheduledTaskEditor(editing);
82 + expect(takeScheduledTaskNewLink(newTaskLink)).toBe(newTaskLink);
83 + expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)).toBeNull();
84 + });
85 +
86 + it("keeps unsaved changes until the editor's removal guard discards them", () => {
87 + startScheduledTaskEditor(editing);
88 + const edited = { ...editing, draft: { ...editing.draft, prompt: "unsaved" } };
89 + updateScheduledTaskEditor(edited, null);
90 +
91 + takeScheduledTaskNewLink(newTaskLink);
92 + expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current).toBe(edited);
93 +
94 + discardScheduledTaskEditor();
95 + expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)).toBeNull();
96 + });
97 +
98 + it("starts the new-task screen fresh after the edited task was saved", () => {
99 + startScheduledTaskEditor(editing);
100 + updateScheduledTaskEditor({ ...editing, draft: { ...editing.draft, prompt: "saved" } }, null);
101 + markScheduledTaskEditorSaved();
102 +
103 + takeScheduledTaskNewLink(newTaskLink);
104 + expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)).toBeNull();
105 + });
106 +
107 + it("closes a discarded editor as empty when no new-task link is waiting", () => {
108 + startScheduledTaskEditor(editing);
109 + discardScheduledTaskEditor();
110 + expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current).toBeNull();
111 + });
112 +
113 + it("keeps the editor for links to other screens", () => {
114 + startScheduledTaskEditor(editing);
115 + takeScheduledTaskNewLink({ routes: [{ name: "SettingsSheet" }] });
116 + expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current).toBe(editing);
117 + });
118 +});
apps/mobile/src/features/settings/scheduled-task-editor-state.ts
+59 -1
@@ -1,8 +1,11 @@
1 import type { EnvironmentId } from "@t3tools/contracts";
2 +import type { NavigationState, PartialState } from "@react-navigation/native";
3 import { Atom } from "effect/reactivity";
4
5 +import { findLinkedRoute } from "../../lib/appLinking";
6 +
7 import { appAtomRegistry } from "../../state/atom-registry";
5 -import type { ScheduledTaskDraft } from "./scheduledTaskDraft";
8 +import { hasScheduledTaskDraftChanges, type ScheduledTaskDraft } from "./scheduledTaskDraft";
9
10 export type ScheduledTaskEditor = {
11 readonly environmentId: EnvironmentId;
@@ -20,8 +23,22 @@ export const scheduledTaskEditorSessionAtom = Atom.make<ScheduledTaskEditorSessi
23 null,
24 ).pipe(Atom.keepAlive);
25 let nextEditorId = 0;
26 +let newTaskLinkAwaitsDiscard = false;
27 +
28 +export function scheduledTaskEditorHasChanges(
29 + initial: ScheduledTaskEditor | null,
30 + current: ScheduledTaskEditor | null,
31 +): boolean {
32 + return Boolean(
33 + initial &&
34 + current &&
35 + (initial.environmentId !== current.environmentId ||
36 + hasScheduledTaskDraftChanges(initial.draft, current.draft)),
37 + );
38 +}
39
40 export function startScheduledTaskEditor(next: ScheduledTaskEditor | null): void {
41 + newTaskLinkAwaitsDiscard = false;
42 appAtomRegistry.set(scheduledTaskEditorSessionAtom, {
43 id: ++nextEditorId,
44 initial: next,
@@ -45,6 +62,18 @@ export function updateScheduledTaskEditor(
62 });
63 }
64
65 +/**
66 + * A saved task is the new baseline. Without it a later new-task link reads the saved edits as
67 + * unsaved, keeps them under "New", and saving there would overwrite the task.
68 + */
69 +export function markScheduledTaskEditorSaved(): void {
70 + newTaskLinkAwaitsDiscard = false;
71 + const session = appAtomRegistry.get(scheduledTaskEditorSessionAtom);
72 + if (session) {
73 + appAtomRegistry.set(scheduledTaskEditorSessionAtom, { ...session, initial: session.current });
74 + }
75 +}
76 +
77 export function readScheduledTaskEditor(
78 voiceOwnerKey: string,
79 defaultEditor: ScheduledTaskEditor | null,
@@ -53,3 +82,32 @@ export function readScheduledTaskEditor(
82 if (`scheduled-task:${session?.id ?? 0}` !== voiceOwnerKey) return null;
83 return session ? session.current : defaultEditor;
84 }
85 +
86 +/**
87 + * A new-task link starts a fresh editor, or a warm app reopens the last task's draft under
88 + * "New" and saves over it. Links parse before the open editor's removal guard runs, so
89 + * unsaved changes stay until the user discards them there.
90 + */
91 +export function takeScheduledTaskNewLink(
92 + state: PartialState<NavigationState> | undefined,
93 +): PartialState<NavigationState> | undefined {
94 + if (findLinkedRoute(state, ["SettingsScheduledTaskNew"])) {
95 + const session = appAtomRegistry.get(scheduledTaskEditorSessionAtom);
96 + if (session && scheduledTaskEditorHasChanges(session.initial, session.current)) {
97 + newTaskLinkAwaitsDiscard = true;
98 + } else {
99 + appAtomRegistry.set(scheduledTaskEditorSessionAtom, null);
100 + }
101 + }
102 + return state;
103 +}
104 +
105 +/** Drops unsaved changes; a new-task link that waited on them then opens a fresh editor. */
106 +export function discardScheduledTaskEditor(): void {
107 + if (newTaskLinkAwaitsDiscard) {
108 + newTaskLinkAwaitsDiscard = false;
109 + appAtomRegistry.set(scheduledTaskEditorSessionAtom, null);
110 + return;
111 + }
112 + startScheduledTaskEditor(null);
113 +}
apps/mobile/src/features/settings/scheduled-task-editor.tsx
+3 -11
@@ -3,15 +3,12 @@ import type { EnvironmentId } from "@t3tools/contracts";
3 import { useMemo, useCallback, type Dispatch, type SetStateAction } from "react";
4
5 import { useProjects, useServerConfigs } from "../../state/entities";
6 -import {
7 - createDraft,
8 - scheduledTaskDefaultModel,
9 - hasScheduledTaskDraftChanges,
10 -} from "./scheduledTaskDraft";
6 +import { createDraft, scheduledTaskDefaultModel } from "./scheduledTaskDraft";
7 import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
8 import { settingsTargetsForProject } from "./settings-environment-filter.logic";
9
10 import {
11 + scheduledTaskEditorHasChanges,
12 scheduledTaskEditorSessionAtom,
13 startScheduledTaskEditor,
14 updateScheduledTaskEditor,
@@ -64,12 +61,7 @@ export function useScheduledTaskEditor() {
61 const voiceOwnerKey = `scheduled-task:${session?.id ?? 0}`;
62 const editor = session ? session.current : defaultEditor;
63 const initial = session ? session.initial : defaultEditor;
67 - const hasChanges = Boolean(
68 - initial &&
69 - editor &&
70 - (initial.environmentId !== editor.environmentId ||
71 - hasScheduledTaskDraftChanges(initial.draft, editor.draft)),
72 - );
64 + const hasChanges = scheduledTaskEditorHasChanges(initial, editor);
65 const setEditor = useCallback<Dispatch<SetStateAction<ScheduledTaskEditor | null>>>(
66 (update) => {
67 updateScheduledTaskEditor(update, defaultEditor);
apps/mobile/src/features/settings/settings-environment-filter.tsx
+28 -6
@@ -2,8 +2,10 @@ import type { EnvironmentId } from "@t3tools/contracts";
2 import { buildProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
3 import {
4 createContext,
5 + useCallback,
6 useContext,
7 useMemo,
8 + useRef,
9 useState,
10 type Dispatch,
11 type ReactNode,
@@ -57,7 +59,9 @@ interface SettingsEnvironmentSelection {
59 readonly selectedIds: ReadonlySet<EnvironmentId> | null;
60 readonly selectedProjectKey: string | null;
61 readonly setSelectedIds: Dispatch<SetStateAction<ReadonlySet<EnvironmentId> | null>>;
60 - readonly setSelectedProjectKey: Dispatch<SetStateAction<string | null>>;
62 + readonly selectProject: (projectKey: string | null) => void;
63 + /** The selection as of now, for async work that outlives the render it started in. */
64 + readonly getSelectedProjectKey: () => string | null;
65 }
66
67 const SettingsEnvironmentSelectionContext = createContext<SettingsEnvironmentSelection | null>(
@@ -76,13 +80,28 @@ export function SettingsEnvironmentFilterProvider(props: {
80 }) {
81 const [selectedIds, setSelectedIds] = useState<ReadonlySet<EnvironmentId> | null>(null);
82 const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
83 + // Written only by selectProject, so it can keep a key that the close reset below cleared.
84 + // Its one reader, a project removal that finishes after Settings closed, then clears an
85 + // already empty selection, which is harmless.
86 + const currentProjectKey = useRef<string | null>(null);
87 if (!props.open && (selectedIds !== null || selectedProjectKey !== null)) {
88 setSelectedIds(null);
89 setSelectedProjectKey(null);
90 }
91 + const selectProject = useCallback((projectKey: string | null) => {
92 + currentProjectKey.current = projectKey;
93 + setSelectedProjectKey(projectKey);
94 + }, []);
95 + const getSelectedProjectKey = useCallback(() => currentProjectKey.current, []);
96 const value = useMemo(
84 - () => ({ selectedIds, selectedProjectKey, setSelectedIds, setSelectedProjectKey }),
85 - [selectedIds, selectedProjectKey],
97 + () => ({
98 + selectedIds,
99 + selectedProjectKey,
100 + setSelectedIds,
101 + selectProject,
102 + getSelectedProjectKey,
103 + }),
104 + [selectedIds, selectedProjectKey, selectProject, getSelectedProjectKey],
105 );
106 return (
107 <SettingsEnvironmentSelectionContext value={value}>
@@ -94,7 +113,8 @@ export function SettingsEnvironmentFilterProvider(props: {
113 export function useSettingsEnvironmentFilter() {
114 const selection = useContext(SettingsEnvironmentSelectionContext);
115 if (selection === null) throw new Error("Settings environment filter provider is missing.");
97 - const { selectedIds, selectedProjectKey, setSelectedIds, setSelectedProjectKey } = selection;
116 + const { selectedIds, selectedProjectKey, setSelectedIds, selectProject, getSelectedProjectKey } =
117 + selection;
118 const { environments } = useEnvironments();
119 const projects = useProjects();
120 const groupingSettings = useMobileProjectGroupingSettings();
@@ -125,7 +145,8 @@ export function useSettingsEnvironmentFilter() {
145 projectGroups,
146 selectableProjectGroups,
147 selectedProjectKey,
128 - selectProject: setSelectedProjectKey,
148 + selectProject,
149 + getSelectedProjectKey,
150 selectAll: () => setSelectedIds(null),
151 toggleEnvironment: (environmentId: EnvironmentId) =>
152 setSelectedIds((current) =>
@@ -140,7 +161,8 @@ export function useSettingsEnvironmentFilter() {
161 selectableProjectGroups,
162 selectedProjectKey,
163 setSelectedIds,
143 - setSelectedProjectKey,
164 + selectProject,
165 + getSelectedProjectKey,
166 ],
167 );
168 }
apps/mobile/src/features/usage/UsageLimitsSection.test.ts deleted
-121
@@ -1,121 +0,0 @@
1 -import { EnvironmentId } from "@t3tools/contracts";
2 -import { beforeEach, expect, it, vi } from "vite-plus/test";
3 -
4 -const state = vi.hoisted(() => ({
5 - values: [] as unknown[],
6 - cursor: 0,
7 - presentations: new Map(),
8 - refreshProviders: vi.fn(),
9 - autoRefresh: async () => {},
10 - refreshingRef: { current: false },
11 -}));
12 -vi.mock("../../state/session", () => ({
13 - useEnvironmentScope: () => true,
14 - readEnvironmentScope: () => true,
15 -}));
16 -vi.mock("react", () => ({
17 - useState: (initial: unknown) => {
18 - const index = state.cursor++;
19 - if (!(index in state.values)) {
20 - state.values[index] = typeof initial === "function" ? initial() : initial;
21 - }
22 - return [
23 - state.values[index],
24 - (next: unknown) => {
25 - state.values[index] = typeof next === "function" ? next(state.values[index]) : next;
26 - },
27 - ];
28 - },
29 - useRef: () => state.refreshingRef,
30 - useEffect: () => {},
31 - useEffectEvent: (callback: () => Promise<void>) => {
32 - state.autoRefresh = callback;
33 - return callback;
34 - },
35 -}));
36 -vi.mock("@effect/atom-react", () => ({ useAtomValue: () => state.presentations }));
37 -vi.mock("react-native", () => ({ Alert: {}, Pressable: "button", View: "div" }));
38 -vi.mock("../../components/ui/AppText", () => ({ AppText: "span" }));
39 -vi.mock("../../components/ProviderIcon", () => ({ ProviderIcon: () => null }));
40 -vi.mock("./usageProviders", () => ({ useProviderColors: () => ({}) }));
41 -vi.mock("../../state/presentation", () => ({
42 - environmentPresentations: { presentationsAtom: null },
43 -}));
44 -vi.mock("../../state/server", () => ({ serverEnvironment: { refreshProviders: null } }));
45 -vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.refreshProviders }));
46 -
47 -import { useRefreshLimits } from "./UsageLimitsSection";
48 -import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
49 -
50 -beforeEach(() => {
51 - state.values = [];
52 - state.cursor = 0;
53 - state.refreshingRef.current = false;
54 - state.refreshProviders.mockReset();
55 -});
56 -
57 -it("keeps a newer environment failure when an older refresh finishes", async () => {
58 - const a = EnvironmentId.make("mobile-limits-a");
59 - const b = EnvironmentId.make("mobile-limits-b");
60 - const pending = Promise.withResolvers<{ _tag: string }>();
61 - const read = () => {
62 - state.cursor = 0;
63 - return useRefreshLimits();
64 - };
65 - const presentation = (label: string) => ({
66 - connection: { phase: "connected" },
67 - entry: { target: { label } },
68 - });
69 - state.presentations = new Map([[a, presentation("A")]]);
70 - state.refreshProviders.mockImplementation(({ environmentId }) =>
71 - environmentId === a ? pending.promise : Promise.resolve({ _tag: "Failure" }),
72 - );
73 - const first = read().refresh();
74 - state.presentations = new Map([
75 - [a, presentation("A")],
76 - [b, presentation("B")],
77 - ]);
78 - read();
79 - await state.autoRefresh();
80 - expect(read().failedLabels).toEqual(["B"]);
81 - pending.resolve({ _tag: "Success" });
82 - await first;
83 - expect(read().failedLabels).toEqual(["B"]);
84 -});
85 -
86 -it("does not let an older multi-environment batch clear a newer failure for the same environment", async () => {
87 - const a = EnvironmentId.make("mobile-limits-race-a");
88 - const b = EnvironmentId.make("mobile-limits-race-b");
89 - const aFirst = Promise.withResolvers<{ _tag: string }>();
90 - const bFirst = Promise.withResolvers<{ _tag: string }>();
91 - const read = (selected: ReadonlySet<EnvironmentId> | null = null) => {
92 - state.cursor = 0;
93 - return useRefreshLimits(selected);
94 - };
95 - const presentation = (label: string) => ({
96 - connection: { phase: "connected" },
97 - entry: { target: { label } },
98 - });
99 - state.presentations = new Map([
100 - [a, presentation("A")],
101 - [b, presentation("B")],
102 - ]);
103 - let aCalls = 0;
104 - state.refreshProviders.mockImplementation(({ environmentId }) =>
105 - environmentId === b
106 - ? bFirst.promise
107 - : ++aCalls === 1
108 - ? aFirst.promise
109 - : Promise.resolve({ _tag: "Failure" }),
110 - );
111 - read();
112 - const older = state.autoRefresh();
113 - aFirst.resolve({ _tag: "Success" });
114 - await refreshUsageLimits(a, () => aFirst.promise);
115 - const selected = new Set([a]);
116 - await read(selected).refresh();
117 - expect(read(selected).failedLabels).toEqual(["A"]);
118 - bFirst.resolve({ _tag: "Success" });
119 - await older;
120 - expect(read(selected).failedLabels).toEqual(["A"]);
121 -});
apps/mobile/src/features/usage/UsageLimitsSection.tsx
+37 -55
@@ -1,5 +1,5 @@
1 import * as Dialog from "../../components/ui/Dialog";
2 -import { useAtomValue } from "@effect/atom-react";
2 +import { RegistryContext, useAtomMount, useAtomValue } from "@effect/atom-react";
3 import {
4 AuthProvidersManageScope,
5 type EnvironmentId,
@@ -17,8 +17,8 @@ import {
17 paceRemainingPercent,
18 remainingPercent,
19 } from "@t3tools/shared/usageLimits";
20 -import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
21 -import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
20 +import { type ReactNode, useContext, useRef, useState } from "react";
21 +import { Atom } from "effect/reactivity";
22 import { Linking, Pressable, View } from "react-native";
23
24 import { AppText as Text } from "../../components/ui/AppText";
@@ -27,6 +27,13 @@ import { environmentPresentations } from "../../state/presentation";
27 import { serverEnvironment } from "../../state/server";
28 import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
29 import { useAtomCommand } from "../../state/use-atom-command";
30 +import { useNowMinuteMs } from "../../lib/clock";
31 +import {
32 + environmentIdsKey,
33 + limitsAutoRefreshSetAtom,
34 + limitsRefreshFailuresAtom,
35 + refreshEnvironmentLimits,
36 +} from "./usageLimitsRefresh";
37 import { usageProviderKind, useProviderColors } from "./usageProviders";
38
39 const PACE_LABEL = { ahead: "ahead of pace", on: "on pace", under: "under pace" } as const;
@@ -308,79 +315,54 @@ export function ResetCredits(props: {
315 );
316 }
317
318 +const IDLE_ATOM = Atom.make(undefined);
319 +
320 export function useRefreshLimits(
321 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
322 active = false,
323 ) {
324 + const registry = useContext(RegistryContext);
325 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
316 - const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
317 - reportFailure: false,
318 - });
319 - const [now, setNow] = useState(() => Date.now());
326 + const now = useNowMinuteMs();
327 const [refreshing, setRefreshing] = useState(false);
328 const refreshingRef = useRef(false);
322 - const [failedEnvironments, setFailedEnvironments] = useState<
323 - readonly { environmentId: EnvironmentId; label: string }[]
324 - >([]);
325 - const refresh = async (automatic = false, afterPending = false) => {
326 - const connected = [...presentations].filter(
327 - ([environmentId, presentation]) =>
328 - presentation.connection.phase === "connected" &&
329 - (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
329 + const selected = [...presentations].filter(
330 + ([environmentId]) =>
331 + selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId),
332 + );
333 + const connectedIds = selected
334 + .filter(([, presentation]) => presentation.connection.phase === "connected")
335 + .map(([environmentId]) => environmentId);
336 + const connectedKey = environmentIdsKey(connectedIds);
337 + useAtomMount(active && connectedKey !== "" ? limitsAutoRefreshSetAtom(connectedKey) : IDLE_ATOM);
338 + const failedIds = new Set(
339 + useAtomValue(limitsRefreshFailuresAtom(environmentIdsKey(selected.map(([id]) => id)))),
340 + );
341 + const failedLabels = selected
342 + .filter(([environmentId]) => failedIds.has(environmentId))
343 + .map(([, presentation]) => presentation.entry.target.label);
344 +
345 + const refresh = (afterPending: boolean) =>
346 + Promise.all(
347 + connectedIds.map((environmentId) =>
348 + refreshEnvironmentLimits(registry, environmentId, { afterPending }),
349 + ),
350 );
331 - await Promise.all(
332 - connected.map(async ([environmentId, presentation]) => {
333 - const result = await refreshUsageLimits(
334 - environmentId,
335 - () => refreshProviders({ environmentId, input: {} }),
336 - automatic,
337 - afterPending,
338 - );
339 - if (result === undefined) return;
340 - setFailedEnvironments((previous) => [
341 - ...previous.filter((failed) => failed.environmentId !== environmentId),
342 - ...(result._tag === "Failure"
343 - ? [{ environmentId, label: presentation.entry.target.label }]
344 - : []),
345 - ]);
346 - }),
347 - ).finally(() => setNow(Date.now()));
348 - };
351 // Android RefreshControl needs a true-to-false cycle to stop, even with nothing to probe.
352 const refreshManually = async () => {
353 if (refreshingRef.current) return;
354 refreshingRef.current = true;
355 setRefreshing(true);
354 - await refresh().finally(() => {
356 + await refresh(false).finally(() => {
357 refreshingRef.current = false;
358 setRefreshing(false);
359 });
360 };
359 - const connectedLimitsEnvironments = [...presentations]
360 - .filter(
361 - ([environmentId, presentation]) =>
362 - presentation.connection.phase === "connected" &&
363 - (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
364 - )
365 - .map(([environmentId]) => environmentId)
366 - .sort()
367 - .join(",");
368 - const autoRefreshLimits = useEffectEvent(() => refresh(true));
369 - useEffect(() => {
370 - if (active && connectedLimitsEnvironments) void autoRefreshLimits();
371 - }, [active, connectedLimitsEnvironments]);
372 -
373 - const failedLabels = failedEnvironments
374 - .filter(
375 - ({ environmentId }) =>
376 - selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId),
377 - )
378 - .map(({ label }) => label);
361 return {
362 now,
363 refreshing,
364 failedLabels,
365 refresh: refreshManually,
384 - refreshAfterEnable: () => refresh(false, true),
366 + refreshAfterEnable: () => refresh(true),
367 };
368 }
apps/mobile/src/features/usage/UsageRouteScreen.tsx
+11 -18
@@ -28,19 +28,13 @@ import {
28 formatUsd,
29 makeWindow,
30 } from "@t3tools/shared/usageFormat";
31 -import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
31 +import { useRef, useState, type ReactNode } from "react";
32 import { Platform, Pressable, RefreshControl, View } from "react-native";
33 -import Animated, {
34 - FadeIn,
35 - ReduceMotion,
36 - useAnimatedStyle,
37 - useSharedValue,
38 - withDelay,
39 - withTiming,
40 -} from "react-native-reanimated";
33 +import Animated, { FadeIn, ReduceMotion } from "react-native-reanimated";
34 import { useSafeAreaInsets } from "react-native-safe-area-context";
35
36 import { SegmentedControl } from "../../components/ui/SegmentedControl";
37 +import { useReduceMotionEnabled } from "../../lib/appState";
38 import { AppText as Text } from "../../components/ui/AppText";
39 import { ProviderIcon } from "../../components/ProviderIcon";
40 import { cn } from "../../lib/cn";
@@ -403,15 +397,14 @@ function UsageUpdating({
397 readonly label: string | null;
398 readonly children: ReactNode;
399 }) {
406 - const opacity = useSharedValue(1);
407 - useLayoutEffect(() => {
408 - opacity.set(
409 - dimmed
410 - ? withDelay(150, withTiming(0.5, { duration: 150, reduceMotion: ReduceMotion.System }))
411 - : withTiming(1, { duration: 150, reduceMotion: ReduceMotion.System }),
412 - );
413 - }, [opacity, dimmed]);
414 - const dimStyle = useAnimatedStyle(() => ({ opacity: opacity.get() }));
400 + const reduceMotion = useReduceMotionEnabled();
401 + // The delay keeps a quick refresh from flashing the content.
402 + const dimStyle = {
403 + opacity: dimmed ? 0.5 : 1,
404 + transitionProperty: "opacity",
405 + transitionDuration: reduceMotion ? 0 : 150,
406 + transitionDelay: dimmed ? 150 : 0,
407 + } as const;
408
409 return (
410 <View>
apps/mobile/src/features/usage/usageLimitsRefresh.test.ts new
+100
@@ -0,0 +1,100 @@
1 +import { EnvironmentId } from "@t3tools/contracts";
2 +import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
3 +import * as Cause from "effect/Cause";
4 +import { AsyncResult, AtomRegistry } from "effect/reactivity";
5 +import { expect, it, vi } from "vite-plus/test";
6 +
7 +type RefreshResult = AsyncResult.AsyncResult<void, string>;
8 +
9 +const state = vi.hoisted(() => ({
10 + refresh: (_environmentId: string): Promise<RefreshResult> => {
11 + throw new Error("refresh not set up");
12 + },
13 +}));
14 +vi.mock("../../state/server", () => ({
15 + serverEnvironment: {
16 + refreshProviders: {
17 + label: "refresh providers",
18 + run: (_registry: unknown, input: { readonly environmentId: string }) =>
19 + state.refresh(input.environmentId),
20 + },
21 + },
22 +}));
23 +
24 +import {
25 + environmentIdsKey,
26 + limitsRefreshFailuresAtom,
27 + refreshEnvironmentLimits,
28 +} from "./usageLimitsRefresh";
29 +
30 +const success: RefreshResult = AsyncResult.success(undefined);
31 +const failure: RefreshResult = AsyncResult.failure(Cause.fail("offline"));
32 +
33 +function setup(refresh: (environmentId: string) => Promise<RefreshResult>) {
34 + state.refresh = refresh;
35 + const registry = AtomRegistry.make();
36 + return {
37 + registry,
38 + failures: (ids: readonly EnvironmentId[]) => {
39 + const atom = limitsRefreshFailuresAtom(environmentIdsKey(ids));
40 + registry.mount(atom);
41 + return registry.get(atom);
42 + },
43 + };
44 +}
45 +
46 +it("keeps a newer environment failure when an older refresh finishes", async () => {
47 + const a = EnvironmentId.make("mobile-limits-a");
48 + const b = EnvironmentId.make("mobile-limits-b");
49 + const pending = Promise.withResolvers<RefreshResult>();
50 + const { registry, failures } = setup((environmentId) =>
51 + environmentId === a ? pending.promise : Promise.resolve(failure),
52 + );
53 + failures([a, b]);
54 + const first = refreshEnvironmentLimits(registry, a);
55 + await refreshEnvironmentLimits(registry, b, { automatic: true });
56 + expect(failures([a, b])).toEqual([b]);
57 + pending.resolve(success);
58 + await first;
59 + expect(failures([a, b])).toEqual([b]);
60 +});
61 +
62 +it("does not let an older refresh clear a newer failure for the same environment", async () => {
63 + const a = EnvironmentId.make("mobile-limits-race-a");
64 + const b = EnvironmentId.make("mobile-limits-race-b");
65 + const aFirst = Promise.withResolvers<RefreshResult>();
66 + const bFirst = Promise.withResolvers<RefreshResult>();
67 + let aCalls = 0;
68 + const { registry, failures } = setup((environmentId) =>
69 + environmentId === b
70 + ? bFirst.promise
71 + : ++aCalls === 1
72 + ? aFirst.promise
73 + : Promise.resolve(failure),
74 + );
75 + failures([a, b]);
76 + const older = Promise.all([
77 + refreshEnvironmentLimits(registry, a, { automatic: true }),
78 + refreshEnvironmentLimits(registry, b, { automatic: true }),
79 + ]);
80 + aFirst.resolve(success);
81 + await refreshUsageLimits(a, () => aFirst.promise);
82 + await refreshEnvironmentLimits(registry, a);
83 + expect(failures([a])).toEqual([a]);
84 + bFirst.resolve(success);
85 + await older;
86 + expect(failures([a, b])).toEqual([a]);
87 +});
88 +
89 +it("skips an automatic refresh inside the throttle window without touching the outcome", async () => {
90 + const a = EnvironmentId.make("mobile-limits-throttle");
91 + const { registry, failures } = setup(() => Promise.resolve(failure));
92 + failures([a]);
93 + await refreshEnvironmentLimits(registry, a);
94 + expect(failures([a])).toEqual([a]);
95 + state.refresh = () => Promise.resolve(success);
96 + await refreshEnvironmentLimits(registry, a, { automatic: true });
97 + expect(failures([a])).toEqual([a]);
98 + await refreshEnvironmentLimits(registry, a);
99 + expect(failures([a])).toEqual([]);
100 +});
apps/mobile/src/features/usage/usageLimitsRefresh.ts new
+70
@@ -0,0 +1,70 @@
1 +import { EnvironmentId } from "@t3tools/contracts";
2 +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
3 +import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
4 +import { Atom, type AtomRegistry } from "effect/reactivity";
5 +
6 +import { serverEnvironment } from "../../state/server";
7 +
8 +/**
9 + * Whether the last finished limits refresh for an environment failed. Not kept
10 + * alive: the limits view mounts it, and leaving the view forgets old failures.
11 + */
12 +export const limitsRefreshFailedAtom = Atom.family((environmentId: EnvironmentId) =>
13 + Atom.make(false).pipe(Atom.withLabel(`mobile:limits-refresh-failed:${environmentId}`)),
14 +);
15 +
16 +export async function refreshEnvironmentLimits(
17 + registry: AtomRegistry.AtomRegistry,
18 + environmentId: EnvironmentId,
19 + options: { readonly automatic?: boolean; readonly afterPending?: boolean } = {},
20 +): Promise<void> {
21 + // One refresh runs per environment at a time, so results land in the order
22 + // they were started and the newest outcome always wins.
23 + const result = await refreshUsageLimits(
24 + environmentId,
25 + () =>
26 + runAtomCommand(
27 + registry,
28 + serverEnvironment.refreshProviders,
29 + { environmentId, input: {} },
30 + { reportFailure: false },
31 + ),
32 + options.automatic,
33 + options.afterPending,
34 + );
35 + if (result === undefined) return;
36 + registry.set(limitsRefreshFailedAtom(environmentId), result._tag === "Failure");
37 +}
38 +
39 +// Mounting starts an automatic refresh, which refreshUsageLimits throttles to
40 +// one every few minutes per environment.
41 +const limitsAutoRefreshAtom = Atom.family((environmentId: EnvironmentId) =>
42 + Atom.make((get) => {
43 + void refreshEnvironmentLimits(get.registry, environmentId, { automatic: true });
44 + }).pipe(Atom.withLabel(`mobile:limits-auto-refresh:${environmentId}`)),
45 +);
46 +
47 +export function environmentIdsKey(environmentIds: Iterable<EnvironmentId>): string {
48 + return [...environmentIds].sort().join(",");
49 +}
50 +
51 +function splitEnvironmentIds(key: string): EnvironmentId[] {
52 + return key === "" ? [] : key.split(",").map((id) => EnvironmentId.make(id));
53 +}
54 +
55 +/** Keyed by a sorted, comma-joined id list so equal selections share one atom. */
56 +export const limitsAutoRefreshSetAtom = Atom.family((environmentIds: string) =>
57 + Atom.make((get) => {
58 + for (const environmentId of splitEnvironmentIds(environmentIds)) {
59 + get(limitsAutoRefreshAtom(environmentId));
60 + }
61 + }),
62 +);
63 +
64 +export const limitsRefreshFailuresAtom = Atom.family((environmentIds: string) =>
65 + Atom.make((get) =>
66 + splitEnvironmentIds(environmentIds).filter((environmentId) =>
67 + get(limitsRefreshFailedAtom(environmentId)),
68 + ),
69 + ),
70 +);
apps/mobile/src/lib/appLinking.test.ts
+53 -4
@@ -1,12 +1,12 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { shouldHandleAppLink, restoreDraftLinkState } from "./appLinking";
3 +import { findLinkedRoute, restoreDraftLinkState, shouldHandleAppLink } from "./appLinking";
4
5 describe("shouldHandleAppLink", () => {
6 it.each(["t3code://", "t3code:///", "t3code-dev://", "t3code-preview://"])(
7 "ignores scheme-only URL %s",
8 (url) => {
9 - expect(shouldHandleAppLink(url)).toBe(false);
9 + expect(shouldHandleAppLink(url, true)).toBe(false);
10 },
11 );
12
@@ -15,17 +15,41 @@ describe("shouldHandleAppLink", () => {
15 "t3code://pair?pairingUrl=x",
16 "t3code-dev://settings/usage?tab=limits",
17 ])("handles path-bearing URL %s", (url) => {
18 - expect(shouldHandleAppLink(url)).toBe(true);
18 + expect(shouldHandleAppLink(url, true)).toBe(true);
19 });
20
21 it.each(["t3code://expo-development-client/?url=x", "t3code://expo-sharing/anything"])(
22 "ignores lifecycle URL %s",
23 (url) => {
24 - expect(shouldHandleAppLink(url)).toBe(false);
24 + expect(shouldHandleAppLink(url, true)).toBe(false);
25 },
26 );
27 });
28
29 +describe("cloud-only deep links", () => {
30 + it.each([
31 + "t3code://connect-onboarding",
32 + "t3code-dev://connect-onboarding/?source=x",
33 + "t3code://settings/waitlist",
34 + "t3code://settings/auth",
35 + "exp://192.168.1.2:8081/--/settings/auth",
36 + ])("ignores %s without cloud config", (url) => {
37 + expect(shouldHandleAppLink(url, false)).toBe(false);
38 + expect(shouldHandleAppLink(url, true)).toBe(true);
39 + });
40 +
41 + it.each([
42 + "t3code://settings",
43 + "t3code://settings/authors",
44 + "t3code://pair?next=settings/auth",
45 + "t3code://threads/env/thread/files/scripts/connect-onboarding",
46 + "t3code://new/draft/files/settings/auth",
47 + "exp://192.168.1.2:8081/--/threads/env/thread/files/settings/waitlist",
48 + ])("still handles %s without cloud config", (url) => {
49 + expect(shouldHandleAppLink(url, false)).toBe(true);
50 + });
51 +});
52 +
53 describe("draft deep links", () => {
54 it("opens the old draft URL on the thread screen with its draft identity", () => {
55 const draft = { projectId: "project-1", environmentId: "env-1", draftId: "draft-1" };
@@ -65,3 +89,28 @@ describe("draft deep links", () => {
89 expect(restoreDraftLinkState(undefined, "/new/draft")).toBeUndefined();
90 });
91 });
92 +
93 +describe("nested link routes", () => {
94 + const settingsLink = {
95 + routes: [
96 + { name: "Home" },
97 + {
98 + name: "SettingsSheet",
99 + state: {
100 + routes: [
101 + { name: "Settings" },
102 + { name: "SettingsEnvironmentNew", params: { pairingUrl: "x", autoConnect: "1" } },
103 + ],
104 + },
105 + },
106 + ],
107 + };
108 +
109 + it("finds a route the link opens inside a nested navigator", () => {
110 + expect(findLinkedRoute(settingsLink, ["SettingsEnvironmentNew"])?.params).toEqual({
111 + pairingUrl: "x",
112 + autoConnect: "1",
113 + });
114 + expect(findLinkedRoute(settingsLink, ["ConnectionsNew"])).toBeUndefined();
115 + });
116 +});
apps/mobile/src/lib/appLinking.ts
+32 -2
@@ -6,14 +6,24 @@ import type { NavigationState, PartialState } from "@react-navigation/native";
6 * the launcher, not app navigation. Without this filter it falls through
7 * to the NotFound wildcard route on every dev launch.
8 */
9 -export function shouldHandleAppLink(url: string): boolean {
9 +export function shouldHandleAppLink(url: string, cloudConfigured: boolean): boolean {
10 return (
11 !url.includes("expo-development-client") &&
12 !url.includes("://expo-sharing") &&
13 - !/^t3code(-dev|-preview)?:\/*$/.test(url)
13 + !/^t3code(-dev|-preview)?:\/*$/.test(url) &&
14 + (cloudConfigured || !CLOUD_ONLY_LINK_PATH.test(url.split(/[?#]/)[0] ?? ""))
15 );
16 }
17
18 +/**
19 + * Screens that only exist with T3 Connect configured. A build without it has
20 + * no entry points to them, so a link must not open one empty. Anchored to the
21 + * app-relative path (after `exp://host/--/` in Expo Go) so a file route whose
22 + * path merely ends in one of these names still opens.
23 + */
24 +const CLOUD_ONLY_LINK_PATH =
25 + /^[a-z][\w+.-]*:\/*(?:[^/]*\/--\/)?(?:connect-onboarding|settings\/(?:auth|waitlist))\/*$/i;
26 +
27 /** Keep the published draft URLs while using the root thread screen. */
28 export function restoreDraftLinkState(
29 state: PartialState<NavigationState> | undefined,
@@ -29,3 +39,23 @@ export function restoreDraftLinkState(
39 if (pathname !== "new/draft") routes.push(target);
40 return { ...state, index: routes.length - 1, routes };
41 }
42 +
43 +type LinkState = PartialState<NavigationState>;
44 +type LinkRoute = LinkState["routes"][number];
45 +
46 +function isLinkState(value: unknown): value is LinkState {
47 + return typeof value === "object" && value !== null && Array.isArray((value as LinkState).routes);
48 +}
49 +
50 +/** The first route named one of `names`, at any nesting depth of a parsed link. */
51 +export function findLinkedRoute(
52 + state: LinkState | undefined,
53 + names: ReadonlyArray<string>,
54 +): LinkRoute | undefined {
55 + for (const route of state?.routes ?? []) {
56 + if (names.includes(route.name)) return route;
57 + const nested = isLinkState(route.state) ? findLinkedRoute(route.state, names) : undefined;
58 + if (nested) return nested;
59 + }
60 + return undefined;
61 +}
apps/mobile/src/lib/clock.test.ts new
+9
@@ -0,0 +1,9 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { minuteTickToEpochMs } from "./clock";
4 +
5 +describe("minuteTickToEpochMs", () => {
6 + it("reads the minute tick as UTC regardless of the device timezone", () => {
7 + expect(minuteTickToEpochMs("2026-10-26T02:14")).toBe(Date.UTC(2026, 9, 26, 2, 14));
8 + });
9 +});
apps/mobile/src/lib/clock.ts
+16 -1
@@ -1,4 +1,4 @@
1 -import { deadlineStore } from "@t3tools/client-runtime/clock";
1 +import { deadlineStore, minuteTick } from "@t3tools/client-runtime/clock";
2 import { useSyncExternalStore } from "react";
3
4 /** Re-renders once when `deadlineMs` (epoch ms) is reached; `null` never passes. */
@@ -6,3 +6,18 @@ export function useDeadlinePassed(deadlineMs: number | null): boolean {
6 const store = deadlineStore(deadlineMs);
7 return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
8 }
9 +
10 +/**
11 + * `minuteTick`'s UTC `YYYY-MM-DDTHH:mm` as epoch ms. The snapshot carries no
12 + * offset, and `Date.parse` reads offset-less date-times as local time.
13 + */
14 +export function minuteTickToEpochMs(minute: string): number {
15 + return Date.parse(`${minute}:00Z`);
16 +}
17 +
18 +/** Epoch ms floored to the minute, advancing each wall-clock minute. */
19 +export function useNowMinuteMs(): number {
20 + return minuteTickToEpochMs(
21 + useSyncExternalStore(minuteTick.subscribe, minuteTick.getSnapshot, minuteTick.getSnapshot),
22 + );
23 +}
apps/mobile/src/state/use-remote-environment-registry.ts
+10 -4
@@ -6,6 +6,7 @@ import * as Cause from "effect/Cause";
6 import { AsyncResult, Atom } from "effect/reactivity";
7 import { useCallback } from "react";
8
9 +import { hasCloudPublicConfig } from "../features/cloud/publicConfig";
10 import { useConnectionController } from "../features/connection/useConnectionController";
11 import { environmentPresentations } from "./presentation";
12 import { useWorkspaceConnectionState, useWorkspaceEnvironments } from "./workspace";
@@ -182,10 +183,15 @@ export function useRemoteConnections() {
183 `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.`,
184 [
185 { text: "Cancel", style: "cancel" },
185 - {
186 - text: "Open T3 Account",
187 - onPress: () => navigation.navigate("SettingsAuth"),
188 - },
186 + // SettingsAuth renders nothing in builds without cloud config.
187 + ...(hasCloudPublicConfig()
188 + ? [
189 + {
190 + text: "Open T3 Account",
191 + onPress: () => navigation.navigate("SettingsAuth"),
192 + },
193 + ]
194 + : []),
195 remove,
196 ],
197 );