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

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