Open History to see the last commit
1import { installPermissionUpdateNotice } from "./features/connection/permissionUpdateNotice";
2import { installComposerAttachmentUploads } from "./state/composer-attachment-uploads";
3import { installThreadOutboxDelivery } from "./state/threadOutboxDelivery";
4import * as Linking from "expo-linking";
5import * as SplashScreen from "expo-splash-screen";
6import { requireNativeModule } from "expo";
7import { useEffect, useRef, useState } from "react";
8import { Platform, StatusBar } from "react-native";
9import { GestureHandlerRootView } from "react-native-gesture-handler";
10import { KeyboardProvider } from "react-native-keyboard-controller";
11import { SafeAreaProvider } from "react-native-safe-area-context";
12import {
13 CommonActions,
14 createPathConfigForStaticNavigation,
15 createStaticNavigation,
16 getActionFromState,
17 getStateFromPath,
18 type NavigationAction,
19 type NavigationState,
20} from "@react-navigation/native";
21import { pipe } from "effect/Function";
22import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
23
24import { RegistryContext, useAtomValue } from "@effect/atom-react";
25import { ProjectChipIconRasterizer } from "./native/ProjectChipIconImages";
26import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet";
27import * as Dialog from "./components/ui/Dialog";
28import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
29import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
30import { installShowcaseCapture } from "./features/showcase/ShowcaseCaptureCoordinator";
31import {
32 presentPendingIncomingShare,
33 pruneIncomingShareImports,
34 startIncomingShareInbox,
35} from "./features/sharing/IncomingShareProvider";
36import {
37 installAgentNotificationNavigation,
38 setAgentNotificationPathname,
39} from "./features/agent-awareness/notificationNavigation";
40import {
41 installAppShortcuts,
42 recordAppShortcutNavigationState,
43} from "./features/shortcuts/appShortcutsRuntime";
44import {
45 AppearancePreferencesProvider,
46 installAppearanceRuntime,
47 useAppearancePreferences,
48} from "./features/settings/appearance/AppearancePreferencesProvider";
49import { RootStack, rootPathnameFromState, workspaceLocationFromState } from "./Stack";
50import { appAtomRegistry } from "./state/atom-registry";
51import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts";
52import { environmentThreadShells, threadEnvironment } from "./state/threads";
53import { environmentShell, shellCachesReadAtom } from "./state/shell";
54import { OverlayPortalHost } from "./components/ui/OverlayPortal";
55import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
56import { hasCloudPublicConfig } from "./features/cloud/publicConfig";
57import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state";
58import {
59 pairingFormLinkAction,
60 startDevAutoConnect,
61 withoutPairingTarget,
62} from "./features/connection/devAutoConnect";
63import {
64 resolvePendingNewTaskPromptLink,
65 takeNewTaskPromptLink,
66} from "./features/prompt-links/newTaskPromptLink";
67import {
68 resolvePendingThreadPromptLink,
69 takeThreadPromptLink,
70} from "./features/prompt-links/threadPromptLink";
71import {
72 disposeOnFoundationReplace,
73 type FoundationHotModule,
74} from "./lib/foundation-fast-refresh";
75import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";
76import { installUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc";
77import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator";
78import { ConnectDeviceApprovalCoordinator } from "./features/connection/ConnectDeviceApprovalCoordinator";
79import { installSubscriptionUsageRefresh } from "./widgets/useSubscriptionUsage";
80import { GlobalVoiceInputControl } from "./features/voice-input/GlobalVoiceInputControl";
81import {
82 launchSplashHomeRowsPending,
83 settleLaunchSplashHomeRows,
84 splashCanHide,
85 useLaunchSplashHomeRowsPending,
86} from "./features/home/home-launch-splash";
87import {
88 restoreSettingsLinkState,
89 settingsLinkAction,
90} from "./features/settings/settings-navigation";
91import {
92 hydrateWorkspaceSelections,
93 launchWorkspaceURL,
94 recordWorkspaceSelections,
95 settingsLinkPage,
96} from "./features/layout/workspace/workspace-selection-store";
97import { workspaceDetailLinkAction } from "./features/layout/workspace/workspace-detail-selection";
98import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics";
99import {
100 attachRootNavigation,
101 flushRootNavigationQueue,
102 linkToRootPath,
103 rootNavigationRef,
104} from "./lib/rootNavigation";
105import { pruneNewTaskFlowStates } from "./features/threads/new-task-flow-state";
106import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen";
107import { installAppUpdateChecks } from "./features/updates/app-updates";
108
109import "../global.css";
110
111if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
112 prepareNativeShowcaseCapture();
113}
114
115void SplashScreen.preventAutoHideAsync().catch(() => {});
116void hydrateWorkspaceSelections();
117
118const linkingConfig = {
119 initialRouteName: "Home",
120 screens: createPathConfigForStaticNavigation(RootStack, { initialRouteName: "Home" }) ?? {},
121} as const;
122
123function getAppStateFromPath(path: string, options: Parameters<typeof getStateFromPath>[1]) {
124 return pipe(
125 getStateFromPath(path, options),
126 (state) => restoreDraftLinkState(state, path),
127 (state) => restoreSettingsLinkState(state, settingsLinkPage()),
128 takeThreadPromptLink,
129 takeNewTaskPromptLink,
130 withoutPairingTarget,
131 startDevAutoConnect,
132 takeScheduledTaskNewLink,
133 );
134}
135
136const appLinking = {
137 prefixes: [
138 Linking.createURL("/"),
139 "t3code://",
140 "t3code-dev://",
141 "t3code-preview://",
142 DEFAULT_HOSTED_APP_URL,
143 ],
144 config: { initialRouteName: "Home" },
145 filter: (url: string) => shouldHandleAppLink(url, hasCloudPublicConfig()),
146 getInitialURL: async () => (await Linking.getInitialURL()) ?? (await launchWorkspaceURL()),
147 getActionFromState: (
148 state: Parameters<typeof getActionFromState>[0],
149 options: Parameters<typeof getActionFromState>[1],
150 ): ReturnType<typeof getActionFromState> => {
151 const current = rootNavigationRef.isReady() ? rootNavigationRef.getRootState() : undefined;
152 return (
153 // Our router handles the selection; React Navigation's type only lists its own actions.
154 (workspaceDetailLinkAction(state) as ReturnType<typeof getActionFromState>) ??
155 pairingFormLinkAction(state, current) ??
156 settingsLinkAction(state, current) ??
157 getActionFromState(state, options)
158 );
159 },
160 getStateFromPath: getAppStateFromPath,
161};
162
163function appLinkAction(href: string): NavigationAction {
164 const state = getAppStateFromPath(href, linkingConfig);
165 if (!state) throw new Error(`Failed to parse the href to a navigation state (${href}).`);
166 return appLinking.getActionFromState(state, linkingConfig) ?? CommonActions.reset(state);
167}
168
169function linkToAppPath(href: string): void {
170 linkToRootPath(href, appLinkAction);
171}
172
173const Navigation = createStaticNavigation(RootStack);
174
175function handleNavigationStateChange(state: NavigationState | undefined): void {
176 recordWorkspaceSelections(state);
177 presentPendingIncomingShare();
178 resolvePendingNewTaskPromptLink(state);
179 resolvePendingThreadPromptLink(state);
180 if (!state) return;
181 // A launch that opens another route has no Home rows for the splash to wait for.
182 if (state.routes[state.index]?.name !== "Home") settleLaunchSplashHomeRows();
183 setAgentNotificationPathname(workspaceLocationFromState(state).pathname);
184 recordAppShortcutNavigationState(state);
185 pruneNewTaskFlowStates(state);
186 pruneNewTaskBranchCheckouts(state);
187 pruneIncomingShareImports(state);
188}
189
190function handleNavigationReady(): void {
191 handleNavigationStateChange(rootNavigationRef.getRootState());
192 flushRootNavigationQueue();
193}
194
195declare const module: { readonly hot?: FoundationHotModule } | undefined;
196
197const appServiceDisposers = [
198 installUiRuntimeMemoryWarningGc(),
199 subscribeComposerDraftModelReconciliation({
200 registry: appAtomRegistry,
201 threadShellAtom: environmentThreadShells.threadShellAtom,
202 threadRefsAtom: environmentThreadShells.threadRefsAtom,
203 shellStateAtom: environmentShell.stateAtom,
204 pendingThreadIdsAtom: threadEnvironment.pendingThreadIdsAtom,
205 }),
206 installAppearanceRuntime(),
207 installSubscriptionUsageRefresh(),
208 installPermissionUpdateNotice(),
209 installThreadOutboxDelivery(),
210 installComposerAttachmentUploads(),
211 startIncomingShareInbox(),
212 installAgentNotificationNavigation(linkToAppPath),
213 installAppShortcuts(linkToAppPath),
214 installAppUpdateChecks(),
215 installShowcaseCapture(rootPathnameFromState),
216];
217disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.hot, () => {
218 for (const dispose of appServiceDisposers) dispose();
219});
220
221// Cached shells are local reads that end in a fraction of this time; the limit keeps a failed
222// read, or a list that does not lay out, from holding the splash screen.
223const SPLASH_WAIT_MS = 1_500;
224
225function SplashScreenCoordinator() {
226 const { isReady } = useAppearancePreferences();
227 const shellCachesRead = useAtomValue(shellCachesReadAtom);
228 const homeRowsPending = useLaunchSplashHomeRowsPending();
229 const [waitEnded, setWaitEnded] = useState(false);
230 const hidden = useRef(false);
231
232 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the limit on how long the native splash screen waits for cached shells and their rows
233 useEffect(() => {
234 const timer = setTimeout(() => setWaitEnded(true), SPLASH_WAIT_MS);
235 return () => clearTimeout(timer);
236 }, []);
237
238 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hides the native splash screen once preferences have loaded and the cached rows are laid out
239 useEffect(() => {
240 const canHide = splashCanHide({
241 preferencesReady: isReady,
242 shellCachesRead,
243 // Home holds the splash in a layout effect of the commit that gives it rows. That can be
244 // this commit, after this render read the store.
245 homeRowsPending: homeRowsPending || launchSplashHomeRowsPending(),
246 waitEnded,
247 });
248 if (!canHide || hidden.current) return;
249 hidden.current = true;
250 settleLaunchSplashHomeRows();
251 void SplashScreen.hide();
252 }, [isReady, shellCachesRead, homeRowsPending, waitEnded]);
253
254 return null;
255}
256
257export default function App() {
258 return (
259 <RegistryContext.Provider value={appAtomRegistry}>
260 <CloudAuthProvider>
261 <AppearancePreferencesProvider>
262 <AppContent />
263 </AppearancePreferencesProvider>
264 </CloudAuthProvider>
265 </RegistryContext.Provider>
266 );
267}
268
269function AppContent() {
270 const { themeAppearance } = useAppearancePreferences();
271 const navigationTheme = useMobileNavigationTheme();
272
273 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- matches the Android navigation bar to the app theme, as StatusBar does for the status bar
274 useEffect(() => {
275 if (Platform.OS !== "android") return;
276 void requireNativeModule<{ setNavigationBarStyle(light: boolean): Promise<void> }>(
277 "T3NativeControls",
278 ).setNavigationBarStyle(themeAppearance === "light");
279 }, [themeAppearance]);
280
281 return (
282 <>
283 <SplashScreenCoordinator />
284 <SubscriptionUsageCoordinator />
285 <ConnectDeviceApprovalCoordinator />
286 <GestureHandlerRootView className="flex-1">
287 <KeyboardProvider statusBarTranslucent>
288 <SafeAreaProvider>
289 <StatusBar barStyle={themeAppearance === "dark" ? "light-content" : "dark-content"} />
290 {/* native-stack needs the theme's dark flag to select dark native headers. */}
291 <GlobalVoiceInputControl>
292 <NativeLayoutMetricsProvider>
293 <Navigation
294 ref={attachRootNavigation}
295 linking={appLinking}
296 onReady={handleNavigationReady}
297 theme={navigationTheme}
298 onStateChange={handleNavigationStateChange}
299 />
300 <Dialog.Host />
301 <ThreadArrangementHost />
302 <ProjectChipIconRasterizer />
303 </NativeLayoutMetricsProvider>
304 </GlobalVoiceInputControl>
305 <OverlayPortalHost />
306 </SafeAreaProvider>
307 </KeyboardProvider>
308 </GestureHandlerRootView>
309 </>
310 );
311}