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

__root.tsx

347 lines11.2 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 {
17 SlowRpcAckToastCoordinator,
18 WebSocketConnectionCoordinator,
19 WebSocketConnectionSurface,
20} from "../components/WebSocketConnectionSurface";
21import { Button } from "../components/ui/button";
22import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
23import { resolveAndPersistPreferredEditor } from "../editorPreferences";
24import { readLocalApi } from "../localApi";
25import { useSettings } from "../hooks/useSettings";
26import {
27 deriveLogicalProjectKeyFromSettings,
28 derivePhysicalProjectKeyFromPath,
29} from "../logicalProject";
30import {
31 getServerConfigUpdatedNotification,
32 ServerConfigUpdatedNotification,
33 startServerStateSync,
34 useServerConfig,
35 useServerConfigUpdatedSubscription,
36 useServerWelcomeSubscription,
37} from "../rpc/serverState";
38import { useStore } from "../store";
39import { useUiStateStore } from "../uiStateStore";
40import { syncBrowserChromeTheme } from "../hooks/useTheme";
41import {
42 ensureEnvironmentConnectionBootstrapped,
43 getPrimaryEnvironmentConnection,
44 startEnvironmentConnectionService,
45} from "../environments/runtime";
46import { configureClientTracing } from "../observability/clientTracing";
47import {
48 ensurePrimaryEnvironmentReady,
49 resolveInitialServerAuthGateState,
50 updatePrimaryEnvironmentDescriptor,
51} from "../environments/primary";
52​
53export const Route = createRootRouteWithContext<{
54 queryClient: QueryClient;
55}>()({
56 beforeLoad: async () => {
57 const [, authGateState] = await Promise.all([
58 ensurePrimaryEnvironmentReady(),
59 resolveInitialServerAuthGateState(),
60 ]);
61 return {
62 authGateState,
63 };
64 },
65 component: RootRouteView,
66 errorComponent: RootRouteErrorView,
67 head: () => ({
68 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
69 }),
70});
71​
72function RootRouteView() {
73 const pathname = useLocation({ select: (location) => location.pathname });
74 const { authGateState } = Route.useRouteContext();
75​
76 useEffect(() => {
77 const frame = window.requestAnimationFrame(() => {
78 syncBrowserChromeTheme();
79 });
80 return () => {
81 window.cancelAnimationFrame(frame);
82 };
83 }, [pathname]);
84​
85 if (pathname === "/pair") {
86 return <Outlet />;
87 }
88​
89 if (authGateState.status !== "authenticated") {
90 return <Outlet />;
91 }
92 return (
93 <ToastProvider>
94 <AnchoredToastProvider>
95 <AuthenticatedTracingBootstrap />
96 <ServerStateBootstrap />
97 <EnvironmentConnectionManagerBootstrap />
98 <EventRouter />
99 <WebSocketConnectionCoordinator />
100 <SlowRpcAckToastCoordinator />
101 <WebSocketConnectionSurface>
102 <CommandPalette>
103 <AppSidebarLayout>
104 <Outlet />
105 </AppSidebarLayout>
106 </CommandPalette>
107 </WebSocketConnectionSurface>
108 </AnchoredToastProvider>
109 </ToastProvider>
110 );
112​
113function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
114 const message = errorMessage(error);
115 const details = errorDetails(error);
116​
117 return (
118 <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
119 <div className="pointer-events-none absolute inset-0 opacity-80">
120 <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)]" />
121 <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
122 </div>
123​
124 <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">
125 <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
126 {APP_DISPLAY_NAME}
127 </p>
128 <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
129 Something went wrong.
130 </h1>
131 <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
132​
133 <div className="mt-5 flex flex-wrap gap-2">
134 <Button size="sm" onClick={() => reset()}>
135 Try again
136 </Button>
137 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
138 Reload app
139 </Button>
140 </div>
141​
142 <details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
143 <summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
144 <span className="group-open:hidden">Show error details</span>
145 <span className="hidden group-open:inline">Hide error details</span>
146 </summary>
147 <pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
148 {details}
149 </pre>
150 </details>
151 </section>
152 </div>
153 );
155​
156function errorMessage(error: unknown): string {
157 if (error instanceof Error && error.message.trim().length > 0) {
158 return error.message;
159 }
160​
161 if (typeof error === "string" && error.trim().length > 0) {
162 return error;
163 }
164​
165 return "An unexpected router error occurred.";
167​
168function errorDetails(error: unknown): string {
169 if (error instanceof Error) {
170 return error.stack ?? error.message;
171 }
172​
173 if (typeof error === "string") {
174 return error;
175 }
176​
177 try {
178 return JSON.stringify(error, null, 2);
179 } catch {
180 return "No additional error details are available.";
181 }
183​
184function ServerStateBootstrap() {
185 useEffect(() => startServerStateSync(getPrimaryEnvironmentConnection().client.server), []);
186​
187 return null;
189​
190function AuthenticatedTracingBootstrap() {
191 useEffect(() => {
192 void configureClientTracing();
193 }, []);
194​
195 return null;
197​
198function EnvironmentConnectionManagerBootstrap() {
199 const queryClient = useQueryClient();
200​
201 useEffect(() => {
202 return startEnvironmentConnectionService(queryClient);
203 }, [queryClient]);
204​
205 return null;
207​
208function EventRouter() {
209 const setActiveEnvironmentId = useStore((store) => store.setActiveEnvironmentId);
210 const navigate = useNavigate();
211 const pathname = useLocation({ select: (loc) => loc.pathname });
212 const projectGroupingSettings = useSettings((settings) => ({
213 sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
214 sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
215 }));
216 const readPathname = useEffectEvent(() => pathname);
217 const handledBootstrapThreadIdRef = useRef<string | null>(null);
218 const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
219 const disposedRef = useRef(false);
220 const serverConfig = useServerConfig();
221​
222 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
223 if (!payload) return;
224​
225 updatePrimaryEnvironmentDescriptor(payload.environment);
226 setActiveEnvironmentId(payload.environment.environmentId);
227 void (async () => {
228 await ensureEnvironmentConnectionBootstrapped(payload.environment.environmentId);
229 if (disposedRef.current) {
230 return;
231 }
232​
233 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
234 return;
235 }
236 const bootstrapEnvironmentState =
237 useStore.getState().environmentStateById[payload.environment.environmentId];
238 const bootstrapProject =
239 bootstrapEnvironmentState?.projectById[payload.bootstrapProjectId] ?? null;
240 const bootstrapProjectKey =
241 (bootstrapProject
242 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
243 : null) ??
244 (serverConfig?.cwd
245 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
246 : null) ??
247 scopedProjectKey(
248 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
249 );
250 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
251​
252 if (readPathname() !== "/") {
253 return;
254 }
255 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
256 return;
257 }
258 await navigate({
259 to: "/$environmentId/$threadId",
260 params: {
261 environmentId: payload.environment.environmentId,
262 threadId: payload.bootstrapThreadId,
263 },
264 replace: true,
265 });
266 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
267 })().catch(() => undefined);
268 });
269​
270 const handleServerConfigUpdated = useEffectEvent(
271 (notification: ServerConfigUpdatedNotification | null) => {
272 if (!notification) return;
273​
274 const { id, payload, source } = notification;
275 if (id <= seenServerConfigUpdateIdRef.current) {
276 return;
277 }
278 seenServerConfigUpdateIdRef.current = id;
279 if (source !== "keybindingsUpdated") {
280 return;
281 }
282​
283 const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
284 if (!issue) {
285 toastManager.add({
286 type: "success",
287 title: "Keybindings updated",
288 description: "Keybindings configuration reloaded successfully.",
289 });
290 return;
291 }
292​
293 toastManager.add({
294 type: "warning",
295 title: "Invalid keybindings configuration",
296 description: issue.message,
297 actionProps: {
298 children: "Open keybindings.json",
299 onClick: () => {
300 const api = readLocalApi();
301 if (!api) {
302 return;
303 }
304​
305 void Promise.resolve(serverConfig ?? api.server.getConfig())
306 .then((config) => {
307 const editor = resolveAndPersistPreferredEditor(config.availableEditors);
308 if (!editor) {
309 throw new Error("No available editors found.");
310 }
311 return api.shell.openInEditor(config.keybindingsConfigPath, editor);
312 })
313 .catch((error) => {
314 toastManager.add({
315 type: "error",
316 title: "Unable to open keybindings file",
317 description:
318 error instanceof Error ? error.message : "Unknown error opening file.",
319 });
320 });
321 },
322 },
323 });
324 },
325 );
326​
327 useEffect(() => {
328 if (!serverConfig) {
329 return;
330 }
331​
332 updatePrimaryEnvironmentDescriptor(serverConfig.environment);
333 setActiveEnvironmentId(serverConfig.environment.environmentId);
334 }, [serverConfig, setActiveEnvironmentId]);
335​
336 useEffect(() => {
337 disposedRef.current = false;
338 return () => {
339 disposedRef.current = true;
340 };
341 }, []);
342​
343 useServerWelcomeSubscription(handleWelcome);
344 useServerConfigUpdatedSubscription(handleServerConfigUpdated);
345​
346 return null;