Open History to see the last commit
1import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
2import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
3import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4import {
5 Outlet,
6 createRootRoute,
7 type ErrorComponentProps,
8 useLocation,
9 useNavigate,
10} from "@tanstack/react-router";
11import { useEffect, useEffectEvent, useRef, useState } from "react";
12
13import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "../branding";
14import { resolveServerBackedAppDisplayName } from "../branding.logic";
15import { AppSidebarLayout } from "../components/AppSidebarLayout";
16import { CommandPalette } from "../components/CommandPalette";
17import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
18import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
19import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
20import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
21import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
22import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
23import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
24import { Button } from "../components/ui/button";
25import {
26 AnchoredToastProvider,
27 stackedThreadToast,
28 ToastProvider,
29 toastManager,
30} from "../components/ui/toast";
31import { resolveAndPersistPreferredEditor } from "../editorPreferences";
32import { applyAppearanceFontVariables } from "~/appearanceFonts";
33import { useClientSettings } from "../hooks/useSettings";
34import {
35 deriveLogicalProjectKeyFromSettings,
36 derivePhysicalProjectKeyFromPath,
37 selectProjectGroupingSettings,
38} from "../logicalProject";
39import { useUiStateStore } from "../uiStateStore";
40import { syncBrowserChromeTheme } from "../hooks/useTheme";
41import { configureClientTracing } from "../observability/clientTracing";
42import { resolveInitialServerAuthGateState } from "../environments/primary";
43import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
44import { shellEnvironment } from "../state/shell";
45import { useAtomValue } from "@effect/atom-react";
46import { useAtomCommand } from "../state/use-atom-command";
47import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
48import {
49 primaryServerConfigAtom,
50 primaryServerConfigEventAtom,
51 primaryServerWelcomeAtom,
52} from "../state/server";
53import { readProject, setActiveEnvironmentId, useActiveEnvironmentId } from "../state/entities";
54import {
55 createKeybindingsUpdateToastController,
56 type KeybindingsUpdateToastController,
57} from "../components/KeybindingsUpdateToast.logic";
58
59export const Route = createRootRoute({
60 beforeLoad: async ({ location }) => {
61 if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
62 return {
63 authGateState: {
64 status: "hosted-pairing",
65 } as const,
66 };
67 }
68
69 if (isHostedStaticApp(new URL(window.location.href))) {
70 return {
71 authGateState: {
72 status: "hosted-static",
73 } as const,
74 };
75 }
76
77 const authGateState = await resolveInitialServerAuthGateState();
78 return {
79 authGateState,
80 };
81 },
82 component: RootRouteView,
83 errorComponent: RootRouteErrorView,
84 head: () => ({
85 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
86 }),
87});
88
89function RootRouteView() {
90 const pathname = useLocation({ select: (location) => location.pathname });
91 const { authGateState } = Route.useRouteContext();
92 const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
93
94 useEffect(() => {
95 const frame = window.requestAnimationFrame(() => {
96 syncBrowserChromeTheme();
97 });
98 return () => {
99 window.cancelAnimationFrame(frame);
100 };
101 }, [pathname]);
102
103 if (pathname === "/pair" || pathname === "/connect" || pathname.startsWith("/connect/")) {
104 return (
105 <>
106 <DocumentTitleSync />
107 <Outlet />
108 </>
109 );
110 }
111
112 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
113 return (
114 <>
115 <DocumentTitleSync />
116 <Outlet />
117 </>
118 );
119 }
120
121 const appShell = (
122 <CommandPalette>
123 <AppSidebarLayout>
124 <Outlet />
125 </AppSidebarLayout>
126 </CommandPalette>
127 );
128
129 return (
130 <ToastProvider>
131 <AnchoredToastProvider>
132 <DocumentTitleSync />
133 <GlassAppearanceSync />
134 <FontAppearanceSync />
135 {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
136 <RelayClientInstallDialog />
137 <ConnectOnboardingDialog />
138 <SshPasswordPromptDialog />
139 <ConfirmDialogHost />
140 <SlowRpcRequestToastCoordinator />
141 <HostedStaticEnvironmentBootstrap />
142 {primaryEnvironmentAuthenticated ? <EventRouter /> : null}
143 {primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
144 {appShell}
145 {/* Above the router: a theme draft is judged by walking the app, so the
146 editor has to survive navigation away from settings. */}
147 <ThemeEditorHost />
148 </AnchoredToastProvider>
149 </ToastProvider>
150 );
151}
152
153function GlassAppearanceSync() {
154 const glassOpacity = useClientSettings((settings) => settings.glassOpacity);
155
156 useEffect(() => {
157 document.documentElement.style.setProperty("--glass-opacity", `${glassOpacity}%`);
158 }, [glassOpacity]);
159
160 return null;
161}
162
163function FontAppearanceSync() {
164 const fontFamilySans = useClientSettings((settings) => settings.fontFamilySans);
165 const fontFamilyCode = useClientSettings((settings) => settings.fontFamilyCode);
166 const fontFamilyComposer = useClientSettings((settings) => settings.fontFamilyComposer);
167 const fontSizeInterface = useClientSettings((settings) => settings.fontSizeInterface);
168 const fontSizePrompt = useClientSettings((settings) => settings.fontSizePrompt);
169 const fontSizeCode = useClientSettings((settings) => settings.fontSizeCode);
170 const fontSmoothing = useClientSettings((settings) => settings.fontSmoothing);
171
172 useEffect(() => {
173 applyAppearanceFontVariables(document.documentElement, {
174 sans: fontFamilySans,
175 code: fontFamilyCode,
176 composer: fontFamilyComposer,
177 sizeInterface: fontSizeInterface,
178 sizePrompt: fontSizePrompt,
179 sizeCode: fontSizeCode,
180 smoothing: fontSmoothing,
181 });
182 }, [
183 fontFamilyCode,
184 fontFamilyComposer,
185 fontFamilySans,
186 fontSizeCode,
187 fontSizeInterface,
188 fontSizePrompt,
189 fontSmoothing,
190 ]);
191
192 return null;
193}
194
195function DocumentTitleSync() {
196 const primaryServerVersion =
197 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
198 const title = resolveServerBackedAppDisplayName({
199 baseName: APP_BASE_NAME,
200 fallbackDisplayName: APP_DISPLAY_NAME,
201 fallbackStageLabel: APP_STAGE_LABEL,
202 primaryServerVersion,
203 });
204
205 useEffect(() => {
206 document.title = title;
207 }, [title]);
208
209 return null;
210}
211
212function HostedStaticEnvironmentBootstrap() {
213 const { environments } = useEnvironments();
214 const activeEnvironmentId = useActiveEnvironmentId();
215
216 useEffect(() => {
217 if (
218 environments.some(
219 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
220 )
221 ) {
222 return;
223 }
224
225 if (activeEnvironmentId) {
226 return;
227 }
228
229 const firstSavedEnvironment = environments[0];
230 if (!firstSavedEnvironment) {
231 return;
232 }
233
234 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
235 }, [activeEnvironmentId, environments]);
236
237 return null;
238}
239
240function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
241 const message = errorMessage(error);
242 const details = errorDetails(error);
243
244 return (
245 <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
246 <div className="pointer-events-none absolute inset-0 opacity-80">
247 <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)]" />
248 <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
249 </div>
250
251 <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">
252 <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
253 {APP_DISPLAY_NAME}
254 </p>
255 <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
256 Something went wrong.
257 </h1>
258 <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
259
260 <div className="mt-5 flex flex-wrap gap-2">
261 <Button size="sm" onClick={() => reset()}>
262 Try again
263 </Button>
264 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
265 Reload app
266 </Button>
267 </div>
268
269 <details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
270 <summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
271 <span className="group-open:hidden">Show error details</span>
272 <span className="hidden group-open:inline">Hide error details</span>
273 </summary>
274 <pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
275 {details}
276 </pre>
277 </details>
278 </section>
279 </div>
280 );
281}
282
283function errorMessage(error: unknown): string {
284 if (error instanceof Error && error.message.trim().length > 0) {
285 return error.message;
286 }
287
288 if (typeof error === "string" && error.trim().length > 0) {
289 return error;
290 }
291
292 return "An unexpected router error occurred.";
293}
294
295function errorDetails(error: unknown): string {
296 if (error instanceof Error) {
297 return error.stack ?? error.message;
298 }
299
300 if (typeof error === "string") {
301 return error;
302 }
303
304 try {
305 return JSON.stringify(error, null, 2);
306 } catch {
307 return "No additional error details are available.";
308 }
309}
310
311function AuthenticatedTracingBootstrap() {
312 useEffect(() => {
313 void configureClientTracing();
314 }, []);
315
316 return null;
317}
318
319function EventRouter() {
320 const navigate = useNavigate();
321 const pathname = useLocation({ select: (loc) => loc.pathname });
322 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
323 const primaryEnvironment = usePrimaryEnvironment();
324 const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
325 reportFailure: false,
326 });
327 const serverConfig = useAtomValue(primaryServerConfigAtom);
328 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
329 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
330 const readPathname = useEffectEvent(() => pathname);
331 const handledBootstrapThreadIdRef = useRef<string | null>(null);
332 const handledConfigEventRef = useRef(serverConfigEvent);
333 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
334 createKeybindingsUpdateToastController({}),
335 );
336
337 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
338 if (!payload) return;
339
340 setActiveEnvironmentId(payload.environment.environmentId);
341 void (async () => {
342 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
343 return;
344 }
345 const bootstrapProject = readProject(
346 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
347 );
348 const bootstrapProjectKey =
349 (bootstrapProject
350 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
351 : null) ??
352 (serverConfig?.cwd
353 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
354 : null) ??
355 scopedProjectKey(
356 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
357 );
358 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
359
360 if (readPathname() !== "/") {
361 return;
362 }
363 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
364 return;
365 }
366 await navigate({
367 to: "/$environmentId/$threadId",
368 params: {
369 environmentId: payload.environment.environmentId,
370 threadId: payload.bootstrapThreadId,
371 },
372 replace: true,
373 });
374 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
375 })().catch(() => undefined);
376 });
377
378 const handleServerConfigUpdated = useEffectEvent(() => {
379 const decision = keybindingsToastController.handle(serverConfigEvent);
380 if (!decision) {
381 return;
382 }
383
384 if (decision._tag === "Success") {
385 toastManager.add({
386 type: "success",
387 title: "Keybindings updated",
388 description: "Keybindings configuration reloaded successfully.",
389 });
390 return;
391 }
392
393 toastManager.add(
394 stackedThreadToast({
395 type: "warning",
396 title: "Invalid keybindings configuration",
397 description: decision.message,
398 actionVariant: "outline",
399 actionProps: {
400 children: "Open keybindings.json",
401 onClick: () => {
402 if (!serverConfig || !primaryEnvironment) {
403 return;
404 }
405
406 const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
407 if (!editor) {
408 return;
409 }
410 void (async () => {
411 const result = await openInEditor({
412 environmentId: primaryEnvironment.environmentId,
413 input: {
414 cwd: serverConfig.keybindingsConfigPath,
415 editor,
416 },
417 });
418 if (result._tag === "Success") {
419 return;
420 }
421 const error = squashAtomCommandFailure(result);
422 toastManager.add(
423 stackedThreadToast({
424 type: "error",
425 title: "Unable to open keybindings file",
426 description:
427 error instanceof Error ? error.message : "Unknown error opening file.",
428 }),
429 );
430 })();
431 },
432 },
433 }),
434 );
435 });
436
437 useEffect(() => {
438 if (!serverConfig) {
439 return;
440 }
441
442 setActiveEnvironmentId(serverConfig.environment.environmentId);
443 }, [serverConfig]);
444
445 useEffect(() => {
446 handleWelcome(serverWelcome);
447 }, [serverWelcome]);
448
449 useEffect(() => {
450 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
451 return;
452 }
453 handledConfigEventRef.current = serverConfigEvent;
454 handleServerConfigUpdated();
455 }, [serverConfigEvent]);
456
457 return null;
458}