Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

__root.tsx

430 lines13.8 KB

1import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
2import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime";
3import {
4 Outlet,
5 createRootRouteWithContext,
6 type ErrorComponentProps,
7 useLocation,
8 useNavigate,
9} from "@tanstack/react-router";
10import { useEffect, useEffectEvent, useRef } from "react";
11import { QueryClient, useQueryClient } from "@tanstack/react-query";
12​
13import { APP_DISPLAY_NAME } from "../branding";
14import { AppSidebarLayout } from "../components/AppSidebarLayout";
15import { CommandPalette } from "../components/CommandPalette";
16import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
17import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
18import {
19 SlowRpcAckToastCoordinator,
20 WebSocketConnectionCoordinator,
21 WebSocketConnectionSurface,
22} from "../components/WebSocketConnectionSurface";
23import { Button } from "../components/ui/button";
24import {
25 AnchoredToastProvider,
26 stackedThreadToast,
27 ToastProvider,
28 toastManager,
29} from "../components/ui/toast";
30import { resolveAndPersistPreferredEditor } from "../editorPreferences";
31import { readLocalApi } from "../localApi";
32import { useSettings } from "../hooks/useSettings";
33import {
34 deriveLogicalProjectKeyFromSettings,
35 derivePhysicalProjectKeyFromPath,
36} from "../logicalProject";
37import {
38 getServerConfigUpdatedNotification,
39 ServerConfigUpdatedNotification,
40 startServerStateSync,
41 useServerConfig,
42 useServerConfigUpdatedSubscription,
43 useServerWelcomeSubscription,
44} from "../rpc/serverState";
45import { useStore } from "../store";
46import { useUiStateStore } from "../uiStateStore";
47import { syncBrowserChromeTheme } from "../hooks/useTheme";
48import {
49 ensureEnvironmentConnectionBootstrapped,
50 getPrimaryEnvironmentConnection,
51 listSavedEnvironmentRecords,
52 waitForSavedEnvironmentRegistryHydration,
53 startEnvironmentConnectionService,
54 useSavedEnvironmentRegistryStore,
55} from "../environments/runtime";
56import { configureClientTracing } from "../observability/clientTracing";
57import {
58 ensurePrimaryEnvironmentReady,
59 getPrimaryKnownEnvironment,
60 resolveInitialServerAuthGateState,
61 updatePrimaryEnvironmentDescriptor,
62} from "../environments/primary";
63import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
64​
65export const Route = createRootRouteWithContext<{
66 queryClient: QueryClient;
67}>()({
68 beforeLoad: async ({ location }) => {
69 if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
70 return {
71 authGateState: {
72 status: "hosted-pairing",
73 } as const,
74 };
75 }
76​
77 if (isHostedStaticApp(new URL(window.location.href))) {
78 await waitForSavedEnvironmentRegistryHydration();
79 return {
80 authGateState: {
81 status: "hosted-static",
82 } as const,
83 };
84 }
85​
86 const [, authGateState] = await Promise.all([
87 ensurePrimaryEnvironmentReady(),
88 resolveInitialServerAuthGateState(),
89 ]);
90 return {
91 authGateState,
92 };
93 },
94 component: RootRouteView,
95 errorComponent: RootRouteErrorView,
96 head: () => ({
97 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
98 }),
99});
100​
101function RootRouteView() {
102 const pathname = useLocation({ select: (location) => location.pathname });
103 const { authGateState } = Route.useRouteContext();
104 const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
105​
106 useEffect(() => {
107 const frame = window.requestAnimationFrame(() => {
108 syncBrowserChromeTheme();
109 });
110 return () => {
111 window.cancelAnimationFrame(frame);
112 };
113 }, [pathname]);
114​
115 if (pathname === "/pair") {
116 return <Outlet />;
117 }
118​
119 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
120 return <Outlet />;
121 }
122​
123 const appShell = (
124 <CommandPalette>
125 <AppSidebarLayout>
126 <Outlet />
127 </AppSidebarLayout>
128 </CommandPalette>
129 );
130​
131 return (
132 <ToastProvider>
133 <AnchoredToastProvider>
134 {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
135 {primaryEnvironmentAuthenticated ? <ServerStateBootstrap /> : null}
136 <EnvironmentConnectionManagerBootstrap />
137 <SshPasswordPromptDialog />
138 <HostedStaticEnvironmentBootstrap />
139 {primaryEnvironmentAuthenticated ? <EventRouter /> : null}
140 {primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
141 {primaryEnvironmentAuthenticated ? <WebSocketConnectionCoordinator /> : null}
142 {primaryEnvironmentAuthenticated ? <SlowRpcAckToastCoordinator /> : null}
143 {primaryEnvironmentAuthenticated ? (
144 <WebSocketConnectionSurface>{appShell}</WebSocketConnectionSurface>
145 ) : (
146 appShell
147 )}
148 </AnchoredToastProvider>
149 </ToastProvider>
150 );
152​
153function HostedStaticEnvironmentBootstrap() {
154 const savedEnvironmentCount = useSavedEnvironmentRegistryStore(
155 (state) => Object.keys(state.byId).length,
156 );
157​
158 useEffect(() => {
159 if (getPrimaryKnownEnvironment()) {
160 return;
161 }
162​
163 const currentActiveEnvironmentId = useStore.getState().activeEnvironmentId;
164 if (currentActiveEnvironmentId) {
165 return;
166 }
167​
168 const firstSavedEnvironment = listSavedEnvironmentRecords()[0];
169 if (!firstSavedEnvironment) {
170 return;
171 }
172​
173 useStore.getState().setActiveEnvironmentId(firstSavedEnvironment.environmentId);
174 }, [savedEnvironmentCount]);
175​
176 return null;
178​
179function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
180 const message = errorMessage(error);
181 const details = errorDetails(error);
182​
183 return (
184 <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
185 <div className="pointer-events-none absolute inset-0 opacity-80">
186 <div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-red-500)_16%,transparent),transparent)]" />
187 <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
188 </div>
189​
190 <section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
191 <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
192 {APP_DISPLAY_NAME}
193 </p>
194 <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
195 Something went wrong.
196 </h1>
197 <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
198​
199 <div className="mt-5 flex flex-wrap gap-2">
200 <Button size="sm" onClick={() => reset()}>
201 Try again
202 </Button>
203 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
204 Reload app
205 </Button>
206 </div>
207​
208 <details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
209 <summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
210 <span className="group-open:hidden">Show error details</span>
211 <span className="hidden group-open:inline">Hide error details</span>
212 </summary>
213 <pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
214 {details}
215 </pre>
216 </details>
217 </section>
218 </div>
219 );
221​
222function errorMessage(error: unknown): string {
223 if (error instanceof Error && error.message.trim().length > 0) {
224 return error.message;
225 }
226​
227 if (typeof error === "string" && error.trim().length > 0) {
228 return error;
229 }
230​
231 return "An unexpected router error occurred.";
233​
234function errorDetails(error: unknown): string {
235 if (error instanceof Error) {
236 return error.stack ?? error.message;
237 }
238​
239 if (typeof error === "string") {
240 return error;
241 }
242​
243 try {
244 return JSON.stringify(error, null, 2);
245 } catch {
246 return "No additional error details are available.";
247 }
249​
250function ServerStateBootstrap() {
251 useEffect(() => {
252 if (!getPrimaryKnownEnvironment()) {
253 return;
254 }
255​
256 return startServerStateSync(getPrimaryEnvironmentConnection().client.server);
257 }, []);
258​
259 return null;
261​
262function AuthenticatedTracingBootstrap() {
263 useEffect(() => {
264 void configureClientTracing();
265 }, []);
266​
267 return null;
269​
270function EnvironmentConnectionManagerBootstrap() {
271 const queryClient = useQueryClient();
272​
273 useEffect(() => {
274 return startEnvironmentConnectionService(queryClient);
275 }, [queryClient]);
276​
277 return null;
279​
280function EventRouter() {
281 const setActiveEnvironmentId = useStore((store) => store.setActiveEnvironmentId);
282 const navigate = useNavigate();
283 const pathname = useLocation({ select: (loc) => loc.pathname });
284 const projectGroupingSettings = useSettings((settings) => ({
285 sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
286 sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
287 }));
288 const readPathname = useEffectEvent(() => pathname);
289 const handledBootstrapThreadIdRef = useRef<string | null>(null);
290 const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
291 const lastKeybindingsSuccessToastAtRef = useRef(0);
292 const disposedRef = useRef(false);
293 const serverConfig = useServerConfig();
294​
295 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
296 if (!payload) return;
297​
298 updatePrimaryEnvironmentDescriptor(payload.environment);
299 setActiveEnvironmentId(payload.environment.environmentId);
300 void (async () => {
301 await ensureEnvironmentConnectionBootstrapped(payload.environment.environmentId);
302 if (disposedRef.current) {
303 return;
304 }
305​
306 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
307 return;
308 }
309 const bootstrapEnvironmentState =
310 useStore.getState().environmentStateById[payload.environment.environmentId];
311 const bootstrapProject =
312 bootstrapEnvironmentState?.projectById[payload.bootstrapProjectId] ?? null;
313 const bootstrapProjectKey =
314 (bootstrapProject
315 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
316 : null) ??
317 (serverConfig?.cwd
318 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
319 : null) ??
320 scopedProjectKey(
321 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
322 );
323 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
324​
325 if (readPathname() !== "/") {
326 return;
327 }
328 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
329 return;
330 }
331 await navigate({
332 to: "/$environmentId/$threadId",
333 params: {
334 environmentId: payload.environment.environmentId,
335 threadId: payload.bootstrapThreadId,
336 },
337 replace: true,
338 });
339 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
340 })().catch(() => undefined);
341 });
342​
343 const handleServerConfigUpdated = useEffectEvent(
344 (notification: ServerConfigUpdatedNotification | null) => {
345 if (!notification) return;
346​
347 const { id, payload, source } = notification;
348 if (id <= seenServerConfigUpdateIdRef.current) {
349 return;
350 }
351 seenServerConfigUpdateIdRef.current = id;
352 if (source !== "keybindingsUpdated") {
353 return;
354 }
355​
356 const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
357 if (!issue) {
358 const now = Date.now();
359 if (now - lastKeybindingsSuccessToastAtRef.current < 2_000) {
360 return;
361 }
362 lastKeybindingsSuccessToastAtRef.current = now;
363 toastManager.add({
364 type: "success",
365 title: "Keybindings updated",
366 description: "Keybindings configuration reloaded successfully.",
367 });
368 return;
369 }
370​
371 toastManager.add(
372 stackedThreadToast({
373 type: "warning",
374 title: "Invalid keybindings configuration",
375 description: issue.message,
376 actionVariant: "outline",
377 actionProps: {
378 children: "Open keybindings.json",
379 onClick: () => {
380 const api = readLocalApi();
381 if (!api) {
382 return;
383 }
384​
385 void Promise.resolve(serverConfig ?? api.server.getConfig())
386 .then((config) => {
387 const editor = resolveAndPersistPreferredEditor(config.availableEditors);
388 if (!editor) {
389 throw new Error("No available editors found.");
390 }
391 return api.shell.openInEditor(config.keybindingsConfigPath, editor);
392 })
393 .catch((error) => {
394 toastManager.add(
395 stackedThreadToast({
396 type: "error",
397 title: "Unable to open keybindings file",
398 description:
399 error instanceof Error ? error.message : "Unknown error opening file.",
400 }),
401 );
402 });
403 },
404 },
405 }),
406 );
407 },
408 );
409​
410 useEffect(() => {
411 if (!serverConfig) {
412 return;
413 }
414​
415 updatePrimaryEnvironmentDescriptor(serverConfig.environment);
416 setActiveEnvironmentId(serverConfig.environment.environmentId);
417 }, [serverConfig, setActiveEnvironmentId]);
418​
419 useEffect(() => {
420 disposedRef.current = false;
421 return () => {
422 disposedRef.current = true;
423 };
424 }, []);
425​
426 useServerWelcomeSubscription(handleWelcome);
427 useServerConfigUpdatedSubscription(handleServerConfigUpdated);
428​
429 return null;