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, 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 { installSubscriptionUsageRefresh } from "./widgets/useSubscriptionUsage";
79import { GlobalVoiceInputControl } from "./features/voice-input/GlobalVoiceInputControl";
80import { restoreSettingsLinkState } from "./features/settings/settings-navigation";
81import {
82 hydrateWorkspaceSelections,
83 launchWorkspaceURL,
84 recordWorkspaceSelections,
85 settingsLinkPage,
86} from "./features/layout/workspace/workspace-selection-store";
87import { workspaceDetailLinkAction } from "./features/layout/workspace/workspace-detail-selection";
88import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics";
89import {
90 attachRootNavigation,
91 flushRootNavigationQueue,
92 linkToRootPath,
93 rootNavigationRef,
94} from "./lib/rootNavigation";
95import { pruneNewTaskFlowStates } from "./features/threads/new-task-flow-state";
96import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen";
97import { installAppUpdateChecks } from "./features/updates/app-updates";
98
99import "../global.css";
100
101if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
102 prepareNativeShowcaseCapture();
103}
104
105void SplashScreen.preventAutoHideAsync().catch(() => {});
106void hydrateWorkspaceSelections();
107
108const linkingConfig = {
109 initialRouteName: "Home",
110 screens: createPathConfigForStaticNavigation(RootStack, { initialRouteName: "Home" }) ?? {},
111} as const;
112
113function getAppStateFromPath(path: string, options: Parameters<typeof getStateFromPath>[1]) {
114 return pipe(
115 getStateFromPath(path, options),
116 (state) => restoreDraftLinkState(state, path),
117 (state) => restoreSettingsLinkState(state, settingsLinkPage()),
118 takeThreadPromptLink,
119 takeNewTaskPromptLink,
120 withoutPairingTarget,
121 startDevAutoConnect,
122 takeScheduledTaskNewLink,
123 );
124}
125
126const appLinking = {
127 prefixes: [
128 Linking.createURL("/"),
129 "t3code://",
130 "t3code-dev://",
131 "t3code-preview://",
132 DEFAULT_HOSTED_APP_URL,
133 ],
134 config: { initialRouteName: "Home" },
135 filter: (url: string) => shouldHandleAppLink(url, hasCloudPublicConfig()),
136 getInitialURL: async () => (await Linking.getInitialURL()) ?? (await launchWorkspaceURL()),
137 getActionFromState: (
138 state: Parameters<typeof getActionFromState>[0],
139 options: Parameters<typeof getActionFromState>[1],
140 ): ReturnType<typeof getActionFromState> =>
141 // Our router handles the selection; React Navigation's type only lists its own actions.
142 (workspaceDetailLinkAction(state) as ReturnType<typeof getActionFromState>) ??
143 pairingFormLinkAction(
144 state,
145 rootNavigationRef.isReady() ? rootNavigationRef.getRootState() : undefined,
146 ) ??
147 getActionFromState(state, options),
148 getStateFromPath: getAppStateFromPath,
149};
150
151function appLinkAction(href: string): NavigationAction {
152 const state = getAppStateFromPath(href, linkingConfig);
153 if (!state) throw new Error(`Failed to parse the href to a navigation state (${href}).`);
154 return appLinking.getActionFromState(state, linkingConfig) ?? CommonActions.reset(state);
155}
156
157function linkToAppPath(href: string): void {
158 linkToRootPath(href, appLinkAction);
159}
160
161const Navigation = createStaticNavigation(RootStack);
162
163function handleNavigationStateChange(state: NavigationState | undefined): void {
164 recordWorkspaceSelections(state);
165 presentPendingIncomingShare();
166 resolvePendingNewTaskPromptLink(state);
167 resolvePendingThreadPromptLink(state);
168 if (!state) return;
169 setAgentNotificationPathname(workspaceLocationFromState(state).pathname);
170 recordAppShortcutNavigationState(state);
171 pruneNewTaskFlowStates(state);
172 pruneNewTaskBranchCheckouts(state);
173 pruneIncomingShareImports(state);
174}
175
176function handleNavigationReady(): void {
177 handleNavigationStateChange(rootNavigationRef.getRootState());
178 flushRootNavigationQueue();
179}
180
181declare const module: { readonly hot?: FoundationHotModule } | undefined;
182
183const appServiceDisposers = [
184 installUiRuntimeMemoryWarningGc(),
185 subscribeComposerDraftModelReconciliation({
186 registry: appAtomRegistry,
187 threadShellAtom: environmentThreadShells.threadShellAtom,
188 threadRefsAtom: environmentThreadShells.threadRefsAtom,
189 shellStateAtom: environmentShell.stateAtom,
190 pendingThreadIdsAtom: threadEnvironment.pendingThreadIdsAtom,
191 }),
192 installAppearanceRuntime(),
193 installSubscriptionUsageRefresh(),
194 installPermissionUpdateNotice(),
195 installThreadOutboxDelivery(),
196 installComposerAttachmentUploads(),
197 startIncomingShareInbox(),
198 installAgentNotificationNavigation(linkToAppPath),
199 installAppShortcuts(linkToAppPath),
200 installAppUpdateChecks(),
201 installShowcaseCapture(rootPathnameFromState),
202];
203disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.hot, () => {
204 for (const dispose of appServiceDisposers) dispose();
205});
206
207// Cached shells are local reads that end in a fraction of this time; the limit only keeps a
208// failed read from holding the splash screen.
209const SPLASH_SHELL_CACHE_WAIT_MS = 1_500;
210
211function SplashScreenCoordinator() {
212 const { isReady } = useAppearancePreferences();
213 const shellCachesRead = useAtomValue(shellCachesReadAtom);
214 const [waitEnded, setWaitEnded] = useState(false);
215
216 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the limit on how long the native splash screen waits for cached shells
217 useEffect(() => {
218 const timer = setTimeout(() => setWaitEnded(true), SPLASH_SHELL_CACHE_WAIT_MS);
219 return () => clearTimeout(timer);
220 }, []);
221
222 // The thread list paints every environment's cached rows at once when the splash hides
223 // after they are read.
224 const canHide = isReady && (shellCachesRead || waitEnded);
225 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hides the native splash screen once preferences and cached shells have loaded
226 useEffect(() => {
227 if (canHide) void SplashScreen.hide();
228 }, [canHide]);
229
230 return null;
231}
232
233export default function App() {
234 return (
235 <RegistryContext.Provider value={appAtomRegistry}>
236 <CloudAuthProvider>
237 <AppearancePreferencesProvider>
238 <AppContent />
239 </AppearancePreferencesProvider>
240 </CloudAuthProvider>
241 </RegistryContext.Provider>
242 );
243}
244
245function AppContent() {
246 const { themeAppearance } = useAppearancePreferences();
247 const navigationTheme = useMobileNavigationTheme();
248
249 // 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
250 useEffect(() => {
251 if (Platform.OS !== "android") return;
252 void requireNativeModule<{ setNavigationBarStyle(light: boolean): Promise<void> }>(
253 "T3NativeControls",
254 ).setNavigationBarStyle(themeAppearance === "light");
255 }, [themeAppearance]);
256
257 return (
258 <>
259 <SplashScreenCoordinator />
260 <SubscriptionUsageCoordinator />
261 <GestureHandlerRootView className="flex-1">
262 <KeyboardProvider statusBarTranslucent>
263 <SafeAreaProvider>
264 <StatusBar barStyle={themeAppearance === "dark" ? "light-content" : "dark-content"} />
265 {/* native-stack needs the theme's dark flag to select dark native headers. */}
266 <GlobalVoiceInputControl>
267 <NativeLayoutMetricsProvider>
268 <Navigation
269 ref={attachRootNavigation}
270 linking={appLinking}
271 onReady={handleNavigationReady}
272 theme={navigationTheme}
273 onStateChange={handleNavigationStateChange}
274 />
275 <Dialog.Host />
276 <ThreadArrangementHost />
277 <ProjectChipIconRasterizer />
278 </NativeLayoutMetricsProvider>
279 </GlobalVoiceInputControl>
280 <OverlayPortalHost />
281 </SafeAreaProvider>
282 </KeyboardProvider>
283 </GestureHandlerRootView>
284 </>
285 );
286}