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

__root.tsx

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