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

__root.tsx

468 lines15.2 KB

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 { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
18import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
19import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
20import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
21import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
22import { Button } from "../components/ui/button";
23import {
24 AnchoredToastProvider,
25 stackedThreadToast,
26 ToastProvider,
27 toastManager,
28} from "../components/ui/toast";
29import { resolveAndPersistPreferredEditor } from "../editorPreferences";
30import { isElectron } from "../env";
31import { useDesktopCaffeination } from "../state/desktopCaffeinate";
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 {isElectron ? <DesktopCaffeinationSync /> : null}
136 {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
137 <RelayClientInstallDialog />
138 <ConnectOnboardingDialog />
139 <SshPasswordPromptDialog />
140 <SlowRpcRequestToastCoordinator />
141 <HostedStaticEnvironmentBootstrap />
142 {primaryEnvironmentAuthenticated ? <EventRouter /> : null}
143 {primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
144 {appShell}
145 </AnchoredToastProvider>
146 </ToastProvider>
147 );
149​
150function DesktopCaffeinationSync() {
151 const enabled = useClientSettings((settings) => settings.caffeinateWhileAgentsRunning);
152 // Mount the driver only while the setting is on so the thread-shell scan and
153 // battery listeners cost nothing in the default (off) configuration; the
154 // driver's unmount cleanup releases any held assertion when it flips off.
155 return enabled ? <DesktopCaffeinationDriver /> : null;
157​
158function DesktopCaffeinationDriver() {
159 useDesktopCaffeination();
160 return null;
162​
163function GlassAppearanceSync() {
164 const glassOpacity = useClientSettings((settings) => settings.glassOpacity);
165​
166 useEffect(() => {
167 document.documentElement.style.setProperty("--glass-opacity", `${glassOpacity}%`);
168 }, [glassOpacity]);
169​
170 return null;
172​
173function FontAppearanceSync() {
174 const fontFamilySans = useClientSettings((settings) => settings.fontFamilySans);
175 const fontFamilyCode = useClientSettings((settings) => settings.fontFamilyCode);
176 const fontFamilyComposer = useClientSettings((settings) => settings.fontFamilyComposer);
177 const fontSizeInterface = useClientSettings((settings) => settings.fontSizeInterface);
178 const fontSizePrompt = useClientSettings((settings) => settings.fontSizePrompt);
179 const fontSizeCode = useClientSettings((settings) => settings.fontSizeCode);
180 const fontSmoothing = useClientSettings((settings) => settings.fontSmoothing);
181​
182 useEffect(() => {
183 applyAppearanceFontVariables(document.documentElement, {
184 sans: fontFamilySans,
185 code: fontFamilyCode,
186 composer: fontFamilyComposer,
187 sizeInterface: fontSizeInterface,
188 sizePrompt: fontSizePrompt,
189 sizeCode: fontSizeCode,
190 smoothing: fontSmoothing,
191 });
192 }, [
193 fontFamilyCode,
194 fontFamilyComposer,
195 fontFamilySans,
196 fontSizeCode,
197 fontSizeInterface,
198 fontSizePrompt,
199 fontSmoothing,
200 ]);
201​
202 return null;
204​
205function DocumentTitleSync() {
206 const primaryServerVersion =
207 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
208 const title = resolveServerBackedAppDisplayName({
209 baseName: APP_BASE_NAME,
210 fallbackDisplayName: APP_DISPLAY_NAME,
211 fallbackStageLabel: APP_STAGE_LABEL,
212 primaryServerVersion,
213 });
214​
215 useEffect(() => {
216 document.title = title;
217 }, [title]);
218​
219 return null;
221​
222function HostedStaticEnvironmentBootstrap() {
223 const { environments } = useEnvironments();
224 const activeEnvironmentId = useActiveEnvironmentId();
225​
226 useEffect(() => {
227 if (
228 environments.some(
229 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
230 )
231 ) {
232 return;
233 }
234​
235 if (activeEnvironmentId) {
236 return;
237 }
238​
239 const firstSavedEnvironment = environments[0];
240 if (!firstSavedEnvironment) {
241 return;
242 }
243​
244 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
245 }, [activeEnvironmentId, environments]);
246​
247 return null;
249​
250function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
251 const message = errorMessage(error);
252 const details = errorDetails(error);
253​
254 return (
255 <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
256 <div className="pointer-events-none absolute inset-0 opacity-80">
257 <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)]" />
258 <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
259 </div>
260​
261 <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">
262 <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
263 {APP_DISPLAY_NAME}
264 </p>
265 <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
266 Something went wrong.
267 </h1>
268 <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
269​
270 <div className="mt-5 flex flex-wrap gap-2">
271 <Button size="sm" onClick={() => reset()}>
272 Try again
273 </Button>
274 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
275 Reload app
276 </Button>
277 </div>
278​
279 <details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
280 <summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
281 <span className="group-open:hidden">Show error details</span>
282 <span className="hidden group-open:inline">Hide error details</span>
283 </summary>
284 <pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
285 {details}
286 </pre>
287 </details>
288 </section>
289 </div>
290 );
292​
293function errorMessage(error: unknown): string {
294 if (error instanceof Error && error.message.trim().length > 0) {
295 return error.message;
296 }
297​
298 if (typeof error === "string" && error.trim().length > 0) {
299 return error;
300 }
301​
302 return "An unexpected router error occurred.";
304​
305function errorDetails(error: unknown): string {
306 if (error instanceof Error) {
307 return error.stack ?? error.message;
308 }
309​
310 if (typeof error === "string") {
311 return error;
312 }
313​
314 try {
315 return JSON.stringify(error, null, 2);
316 } catch {
317 return "No additional error details are available.";
318 }
320​
321function AuthenticatedTracingBootstrap() {
322 useEffect(() => {
323 void configureClientTracing();
324 }, []);
325​
326 return null;
328​
329function EventRouter() {
330 const navigate = useNavigate();
331 const pathname = useLocation({ select: (loc) => loc.pathname });
332 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
333 const primaryEnvironment = usePrimaryEnvironment();
334 const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
335 reportFailure: false,
336 });
337 const serverConfig = useAtomValue(primaryServerConfigAtom);
338 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
339 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
340 const readPathname = useEffectEvent(() => pathname);
341 const handledBootstrapThreadIdRef = useRef<string | null>(null);
342 const handledConfigEventRef = useRef(serverConfigEvent);
343 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
344 createKeybindingsUpdateToastController({}),
345 );
346​
347 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
348 if (!payload) return;
349​
350 setActiveEnvironmentId(payload.environment.environmentId);
351 void (async () => {
352 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
353 return;
354 }
355 const bootstrapProject = readProject(
356 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
357 );
358 const bootstrapProjectKey =
359 (bootstrapProject
360 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
361 : null) ??
362 (serverConfig?.cwd
363 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
364 : null) ??
365 scopedProjectKey(
366 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
367 );
368 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
369​
370 if (readPathname() !== "/") {
371 return;
372 }
373 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
374 return;
375 }
376 await navigate({
377 to: "/$environmentId/$threadId",
378 params: {
379 environmentId: payload.environment.environmentId,
380 threadId: payload.bootstrapThreadId,
381 },
382 replace: true,
383 });
384 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
385 })().catch(() => undefined);
386 });
387​
388 const handleServerConfigUpdated = useEffectEvent(() => {
389 const decision = keybindingsToastController.handle(serverConfigEvent);
390 if (!decision) {
391 return;
392 }
393​
394 if (decision._tag === "Success") {
395 toastManager.add({
396 type: "success",
397 title: "Keybindings updated",
398 description: "Keybindings configuration reloaded successfully.",
399 });
400 return;
401 }
402​
403 toastManager.add(
404 stackedThreadToast({
405 type: "warning",
406 title: "Invalid keybindings configuration",
407 description: decision.message,
408 actionVariant: "outline",
409 actionProps: {
410 children: "Open keybindings.json",
411 onClick: () => {
412 if (!serverConfig || !primaryEnvironment) {
413 return;
414 }
415​
416 const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
417 if (!editor) {
418 return;
419 }
420 void (async () => {
421 const result = await openInEditor({
422 environmentId: primaryEnvironment.environmentId,
423 input: {
424 cwd: serverConfig.keybindingsConfigPath,
425 editor,
426 },
427 });
428 if (result._tag === "Success") {
429 return;
430 }
431 const error = squashAtomCommandFailure(result);
432 toastManager.add(
433 stackedThreadToast({
434 type: "error",
435 title: "Unable to open keybindings file",
436 description:
437 error instanceof Error ? error.message : "Unknown error opening file.",
438 }),
439 );
440 })();
441 },
442 },
443 }),
444 );
445 });
446​
447 useEffect(() => {
448 if (!serverConfig) {
449 return;
450 }
451​
452 setActiveEnvironmentId(serverConfig.environment.environmentId);
453 }, [serverConfig]);
454​
455 useEffect(() => {
456 handleWelcome(serverWelcome);
457 }, [serverWelcome]);
458​
459 useEffect(() => {
460 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
461 return;
462 }
463 handledConfigEventRef.current = serverConfigEvent;
464 handleServerConfigUpdated();
465 }, [serverConfigEvent]);
466​
467 return null;