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

__root.tsx

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