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

__root.tsx

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